Andrew
Andrew

Reputation: 203

Saving file into Azure Blob

I am using below python code to save the file into local folder. I want to save this file into Azure Blob directly. I do not want file to be stored locally and then upload into blob.

I tried giving blob location in folder variable but it did not work. I have excel file that I want to read from Web browser and saved into Azure blobs using python.

 folder = 'Desktop/files/ab'
    
 r = requests.get(api_end_point, headers=api_headers, stream=True)
 with open(folder, 'wb') as f:
    f.write(r.content)

Upvotes: 5

Views: 8889

Answers (1)

suziki
suziki

Reputation: 14080

First you should get the files as something like stream.

import os
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient

connect_str = os.getenv('str')
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = "test"
container_client = blob_service_client.get_container_client(container_name)
blob_client = blob_service_client.get_blob_client(container_name, "MyFirstBlob.txt")
blob_client.upload_blob(req.get_body(), blob_type="BlockBlob")

On my side, I put the data in the body of request, and I upload that to azure blob. It is stream. You can also put a stream in it.

These are the offcial doc:

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python#upload-blobs-to-a-container

https://learn.microsoft.com/en-us/azure/developer/python/sdk/storage/azure-storage-blob/azure.storage.blob.blobserviceclient?view=storage-py-v12

https://learn.microsoft.com/en-us/azure/developer/python/sdk/storage/azure-storage-blob/azure.storage.blob.blobclient?view=storage-py-v12#upload-blob-data--blob-type--blobtype-blockblob---blockblob----length-none--metadata-none----kwargs-

Upvotes: 7

Related Questions