Search code examples
pythonazureazure-storageazure-blob-storage

Create blob container in azure storage if it does not exists


I am trying to create blob container in azure storage using python. I am using documentation provided by MSDN to integrate azure blob storage in my python program.

Here is the code:

connectStr = <connString>
blobServiceClient = BlobServiceClient.from_connection_string(connectStr)
containerName = "quickstart-azureStorage"
localFileName = "quickstart-1.txt"
blobClient = blobServiceClient.create_container(containerName)

create_container() is creating blob container first time, but it is giving me error second time.

I want to create blob container if it does not exists. If it exist then use existing blob container

I am using azure storage library version 12.0.0. i.e azure-storage-blob==12.0.0

I know we can do it for blob present in that container using below code, but I did not find anything for creating container itself.

Check blob exists or not:

blobClient = blobServiceClient.get_blob_client(container=containerName, blob=localFileName)
if blobClient:
    print("blob already exists")
else:
     print("blob not exists")

Exception:

RequestId:<requestId>
Time:2019-12-04T06:59:03.1459600Z
ErrorCode:ContainerAlreadyExists
Error:None

Solution

  • If you are working with a version of azure-storage-blob before 12.8, then a possible solution is to use the get_container_properties function, which will error if the container does not exist.

    This solution was tested with version 12.0.0.

    from azure.storage.blob import ContainerClient
    
    container = ContainerClient.from_connection_string(connectStr, 'foo')
    
    try:
        container_properties = container.get_container_properties()
        # Container foo exists. You can now use it.
    
    except Exception as e:
        # Container foo does not exist. You can now create it.
        container.create_container()
    

    If you are working with a version of azure-storage-blob after 12.8, then you can simply use the exist function, which will return true if the container exist, and false if the container doesn't exist.

    This solution was tested with version 12.8.1.

    from azure.storage.blob import ContainerClient
    
    container = ContainerClient.from_connection_string(connectStr, 'foo')
    
    if container.exists():
        # Container foo exists. You can now use it.
    
    else:
        # Container foo does not exist. You can now create it.
        container.create_container()