Search code examples
djangoazuredjango-rest-frameworkazure-blob-storagedjango-storage

django file upload is not working in azure blob with new version


After updated the azure blob version, it won't install everything. It will install specific version of namespace in the blob. So i installed the following packages.

azure-common==1.1.25
azure-core==1.8.1
azure-nspkg==3.0.2
azure-storage-blob==12.4.0

i'm not able to upload the blob. All the references in the SO and other platforms are for old versions. For new versions there is no reference. The error i'm getting is

    from azure.storage.blob import BlobPermissions, ContentSettings
ImportError: cannot import name 'BlobPermissions' from 'azure.storage.blob'

if i manually went to the path and removed the BlobPermissions from import compilation is happening. But upload is not happening, upload time i'm getting this error

connection_string=self.connection_string)
endpoint_suffix=self.endpoint_suffix)
TypeError: __init__() got an unexpected keyword argument 'token_credential'

Can anyone help me with proper doc for django azure upload with new version. The references i got in SO is manual upload way.

Some reference i got in SO:

  1. Upload and Delete Azure Storage Blob using azure-storage-blob or azure-storage
  2. ImportError: cannot import name 'BlobService' when using Azure Backend

Solution

  • ImportError: cannot import name 'BlobPermissions' from 'azure.storage.blob'

    BlobPermissions is used for the older version. It has replaced with BlobSasPermissions for the new version.


    It seems that django.core.files.storage is not supported by the latest version(3.1). So you could use the older version(e.g. 2.1) to upload file using django, or just use azure-sdk.

    With older version:

    from django.core.files.storage import default_storage
    
    f = open('file.csv', 'rb')
    default_storage.save(path, f)
    

    With Azure SDK:

    from azure.storage.blob import BlobClient
    
    blob = BlobClient.from_connection_string(conn_str="<connection_string>", container_name="my_container", blob_name="my_blob")
    
    with open("file.csv", "rb") as data:
        blob.upload_blob(data)