Search code examples
djangopython-3.xazureazure-storage

How to download data from azure-storage using get_blob_to_stream


I have some files in my azure-storage account. i need to download them using get_blob_to_stream.it is returning azure.storage.blob.models.Blob object. so i couldn't download it by using below code.

def download(request):
    file_name=request.POST['tmtype']
    fp = open(file_name, 'wb')
    generator = block_blob_service.list_blobs(container_name)
    for blob in generator:
        print(blob.name)
        if blob.name==file_name:             
            blob=block_blob_service.get_blob_to_stream(container_name, blob.name, fp,max_connections= 2)    
        response = HttpResponse(blob, content_type="image/png")
        response['Content-Disposition'] = "attachment; filename="+file_name
        return response

Solution

  • You can actually use the get_blob_to_path property, below is an example in python:

    from azure.storage.blob import BlockBlobService
    
    bb = BlockBlobService(account_name='', account_key='')
    container_name = ""
    blob_name_to_download = "test.txt"
    file_path ="/home/Adam/Downloaded_test.txt"
    
    bb.get_blob_to_path(container_name, blob_name_to_download, file_path, open_mode='wb', snapshot=None, start_range=None, end_range=None, validate_content=False, progress_callback=None, max_connections=2, lease_id=None, if_modified_since=None, if_unmodified_since=None, if_match=None, if_none_match=None, timeout=None)
    

    This example with download a blob file named: "test.txt", in a container, to File_path"/home/Adam/Downloaded_test.txt" , you can also keep the same name if you'd like to as well. You can find more samples including this one in https://github.com/adamsmith0016/Azure-storage