Manage container properties and metadata with Python

Blob containers support system properties and user-defined metadata, in addition to the data they contain. This article shows how to manage system properties and user-defined metadata with the Azure Storage client library for Python.

To learn about managing properties and metadata using asynchronous APIs, see Set container metadata 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.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient

Authorization

The authorization mechanism must have the necessary permissions to work with container properties or metadata. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in role Storage Blob Data Reader or higher for the get operations, and Storage Blob Data Contributor or higher for the set operations. To learn more, see the authorization guidance for Get Container Properties (REST API), Set Container Metadata (REST API), or Get Container Metadata (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 properties and metadata

  • System properties: System properties exist on each Blob Storage resource. Some of them can be read or set, while others are read-only. Behind the scenes, some system properties correspond to certain standard HTTP headers. The Azure Storage client library for Python maintains these properties for you.

  • User-defined metadata: User-defined metadata consists of one or more name-value pairs that you specify for a Blob storage resource. You can use metadata to store additional values with the resource. Metadata values are for your own purposes only, and don't affect how the resource behaves.

    Metadata name/value pairs are valid HTTP headers and should adhere to all restrictions governing HTTP headers. For more information about metadata naming requirements, see Metadata names.

Retrieve container properties

To retrieve container properties, use the following method:

The following code example fetches a container's system properties and writes the property values to a console window:

def get_properties(self, blob_service_client: BlobServiceClient, container_name):
    container_client = blob_service_client.get_container_client(container=container_name)

    properties = container_client.get_container_properties()

    print(f"Public access type: {properties.public_access}")
    print(f"Lease status: {properties.lease.status}")
    print(f"Lease state: {properties.lease.state}")
    print(f"Has immutability policy: {properties.has_immutability_policy}")

Set and retrieve metadata

You can specify metadata as one or more name-value pairs on a blob or container resource. To set metadata, use the following method:

Setting container metadata overwrites all existing metadata associated with the container. It's not possible to modify an individual name-value pair.

The following code example sets metadata on a container:

def set_metadata(self, blob_service_client: BlobServiceClient, container_name):
    container_client = blob_service_client.get_container_client(container=container_name)

    # Retrieve existing metadata, if desired
    metadata = container_client.get_container_properties().metadata

    more_metadata = {'docType': 'text', 'docCategory': 'reference'}
    metadata.update(more_metadata)

    # Set metadata on the container
    container_client.set_container_metadata(metadata=metadata)

To retrieve metadata, call the following method:

The following example reads in metadata values:

def get_metadata(self, blob_service_client: BlobServiceClient, container_name):
    container_client = blob_service_client.get_container_client(container=container_name)

    # Retrieve existing metadata, if desired
    metadata = container_client.get_container_properties().metadata

    for k, v in metadata.items():
        print(k, v)

Set container metadata asynchronously

The Azure Blob Storage client library for Python supports managing container properties and metadata asynchronously. To learn more about project setup requirements, see Asynchronous programming.

Follow these steps to set container metadata using asynchronous APIs:

  1. Add the following import statements:

    import asyncio
    
    from azure.identity.aio import DefaultAzureCredential
    from azure.storage.blob.aio import BlobServiceClient
    
  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 sets the container metadata. 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.set_metadata(blob_service_client, "sample-container")
    
    if __name__ == '__main__':
        asyncio.run(main())
    
  3. Add code to set the container metadata. 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 get_container_properties and set_container_metadata methods.

    async def set_metadata(self, blob_service_client: BlobServiceClient, container_name):
        container_client = blob_service_client.get_container_client(container=container_name)
    
        # Retrieve existing metadata, if desired
        metadata = (await container_client.get_container_properties()).metadata
    
        more_metadata = {'docType': 'text', 'docCategory': 'reference'}
        metadata.update(more_metadata)
    
        # Set metadata on the container
        await container_client.set_container_metadata(metadata=metadata)
    

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 setting and retrieving container properties and metadata 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 setting and retrieving properties and metadata use the following REST API operations:

The get_container_properties method retrieves container properties and metadata by calling both the Get Container Properties operation and the Get Container Metadata 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.