แก้ไข

แชร์ผ่าน


List blob containers with Python

When you list the containers in an Azure Storage account from your code, you can specify several options to manage how results are returned from Azure Storage. This article shows how to list containers using the Azure Storage client library for Python.

To learn about listing blob containers using asynchronous APIs, see List containers 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 list blob containers. 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 List Containers (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 listing options

When listing containers from your code, you can specify options to manage how results are returned from Azure Storage. You can specify the number of results to return in each set of results, and then retrieve the subsequent sets. You can also filter the results by a prefix, and return container metadata with the results. These options are described in the following sections.

To list containers in a storage account, call the following method:

This method returns an iterable of type ContainerProperties. Containers are ordered lexicographically by name.

Manage how many results are returned

By default, a listing operation returns up to 5000 results at a time. To return a smaller set of results, provide a nonzero value for the results_per_page keyword argument.

Filter results with a prefix

To filter the list of containers, specify a string or character for the name_starts_with keyword argument. The prefix string can include one or more characters. Azure Storage then returns only the containers whose names start with that prefix.

Include container metadata

To include container metadata with the results, set the include_metadata keyword argument to True. Azure Storage includes metadata with each container returned, so you don't need to fetch the container metadata separately.

Include deleted containers

To include soft-deleted containers with the results, set the include_deleted keyword argument to True.

Code examples

The following example lists all containers and metadata. You can include container metadata by setting include_metadata to True:

def list_containers(self, blob_service_client: BlobServiceClient):
    containers = blob_service_client.list_containers(include_metadata=True)
    for container in containers:
        print(container['name'], container['metadata'])

The following example lists only containers that begin with a prefix specified in the name_starts_with parameter:

def list_containers_prefix(self, blob_service_client: BlobServiceClient):
    containers = blob_service_client.list_containers(name_starts_with='test-')
    for container in containers:
        print(container['name'])

You can also specify a limit for the number of results per page. This example passes in results_per_page and paginates the results:

def list_containers_pages(self, blob_service_client: BlobServiceClient):
    i=0
    all_pages = blob_service_client.list_containers(results_per_page=5).by_page()
    for container_page in all_pages:
        i += 1
        print(f"Page {i}")
        for container in container_page:
            print(container['name'])

List containers asynchronously

The Azure Blob Storage client library for Python supports listing containers asynchronously. To learn more about project setup requirements, see Asynchronous programming.

Follow these steps to list containers 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 lists the containers. 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.list_containers(blob_service_client)
    
    if __name__ == '__main__':
        asyncio.run(main())
    
  3. Add code to list the containers. The code is the same as the synchronous example, except that the method is declared with the async keyword and async for is used when calling the list_containers method.

    async def list_containers(self, blob_service_client: BlobServiceClient):
        async for container in blob_service_client.list_containers(include_metadata=True):
            print(container['name'], container['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 listing containers 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 listing containers use the following REST API operation:

Client library resources

See also

  • 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.