Muokkaa

Jaa


Create a blob container with Python

Blobs in Azure Storage are organized into containers. Before you can upload a blob, you must first create a container. This article shows how to create containers with the Azure Storage client library for Python.

To learn about creating blob containers using asynchronous APIs, see Create a container asynchronously.

Prerequisites

Set up your environment

If you don't have an existing project, this section shows you how to set up a project to work with the Azure Blob Storage client library for Python. For more details, see Get started with Azure Blob Storage and Python.

To work with the code examples in this article, follow these steps to set up your project.

Install packages

Install the following packages using pip install:

pip install azure-storage-blob azure-identity

Add import statements

Add the following import statements:

from azure.core.exceptions import ResourceExistsError
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient

Authorization

The authorization mechanism must have the necessary permissions to create a container. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in role Storage Blob Data Contributor or higher. To learn more, see the authorization guidance for Create Container (REST API).

Create a client object

To connect an app to Blob Storage, create an instance of BlobServiceClient. The following example shows how to create a client object using DefaultAzureCredential for authorization:

# TODO: Replace <storage-account-name> with your actual storage account name
account_url = "https://<storage-account-name>.blob.core.windows.net"
credential = DefaultAzureCredential()

# Create the BlobServiceClient object
blob_service_client = BlobServiceClient(account_url, credential=credential)

You can also create client objects for specific containers or blobs, either directly or from the BlobServiceClient object. To learn more about creating and managing client objects, see Create and manage client objects that interact with data resources.

About container naming

A container name must be a valid DNS name, as it forms part of the unique URI used to address the container or its blobs. Follow these rules when naming a container:

  • Container names can be between 3 and 63 characters long.
  • Container names must start with a letter or number, and can contain only lowercase letters, numbers, and the dash (-) character.
  • Consecutive dash characters aren't permitted in container names.

The URI for a container resource is formatted as follows:

https://my-account-name.blob.core.windows.net/my-container-name

Create a container

To create a container, call the following method from the BlobServiceClient class:

You can also create a container using the following method from the ContainerClient class:

Containers are created immediately beneath the storage account. It's not possible to nest one container beneath another. An exception is thrown if a container with the same name already exists.

The following example creates a container from a BlobServiceClient object:

def create_blob_container(self, blob_service_client: BlobServiceClient, container_name):
    try:
        container_client = blob_service_client.create_container(name=container_name)
    except ResourceExistsError:
        print('A container with this name already exists')

Create the root container

A root container serves as a default container for your storage account. Each storage account may have one root container, which must be named $root. The root container must be explicitly created or deleted.

You can reference a blob stored in the root container without including the root container name. The root container enables you to reference a blob at the top level of the storage account hierarchy. For example, you can reference a blob in the root container as follows:

https://accountname.blob.core.windows.net/default.html

The following example creates a new ContainerClient object with the container name $root, then creates the container if it doesn't already exist in the storage account:

def create_blob_root_container(self, blob_service_client: BlobServiceClient):
    container_client = blob_service_client.get_container_client(container="$root")

    # Create the root container if it doesn't already exist
    if not container_client.exists():
        container_client.create_container()

Create a container asynchronously

The Azure Blob Storage client library for Python supports creating a blob container asynchronously. To learn more about project setup requirements, see Asynchronous programming.

Follow these steps to create a container using asynchronous APIs:

  1. Add the following import statements:

    import asyncio
    
    from azure.identity.aio import DefaultAzureCredential
    from azure.storage.blob.aio import BlobServiceClient
    from azure.core.exceptions import ResourceExistsError
    
  2. Add code to run the program using asyncio.run. This function runs the passed coroutine, main() in our example, and manages the asyncio event loop. Coroutines are declared with the async/await syntax. In this example, the main() coroutine first creates the top level BlobServiceClient using async with, then calls the method that creates the container. Note that only the top level client needs to use async with, as other clients created from it share the same connection pool.

    async def main():
        sample = ContainerSamples()
    
        # TODO: Replace <storage-account-name> with your actual storage account name
        account_url = "https://<storage-account-name>.blob.core.windows.net"
        credential = DefaultAzureCredential()
    
        async with BlobServiceClient(account_url, credential=credential) as blob_service_client:
            await sample.create_blob_container(blob_service_client, "sample-container")
    
    if __name__ == '__main__':
        asyncio.run(main())
    
  3. Add code to create a container. The code is the same as the synchronous example, except that the method is declared with the async keyword and the await keyword is used when calling the create_container method.

    async def create_blob_container(self, blob_service_client: BlobServiceClient, container_name):
        try:
            container_client = await blob_service_client.create_container(name=container_name)
        except ResourceExistsError:
            print('A container with this name already exists')
    

With this basic setup in place, you can implement other examples in this article as coroutines using async/await syntax.

Resources

To learn more about creating a container using the Azure Blob Storage client library for Python, see the following resources.

Code samples

REST API operations

The Azure SDK for Python contains libraries that build on top of the Azure REST API, allowing you to interact with REST API operations through familiar Python paradigms. The client library methods for creating a container use the following REST API operation:

Client library resources

  • This article is part of the Blob Storage developer guide for Python. To learn more, see the full list of developer guide articles at Build your Python app.