Delete and restore a blob container with Python
This article shows how to delete containers with the Azure Storage client library for Python. If you've enabled container soft delete, you can restore deleted containers.
To learn about deleting a blob container using asynchronous APIs, see Delete a container asynchronously.
Prerequisites
- Azure subscription - create one for free
- Azure storage account - create a storage account
- Python 3.8+
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 delete or restore 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 Delete Container (REST API) and Restore 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.
Delete a container
To delete a container in Python, use the following method from the BlobServiceClient class:
You can also delete a container using the following method from the ContainerClient class:
After you delete a container, you can't create a container with the same name for at least 30 seconds. Attempting to create a container with the same name will fail with HTTP error code 409 (Conflict)
. Any other operations on the container or the blobs it contains will fail with HTTP error code 404 (Not Found)
.
The following example uses a BlobServiceClient
object to delete the specified container:
def delete_container(self, blob_service_client: BlobServiceClient, container_name):
container_client = blob_service_client.get_container_client(container=container_name)
container_client.delete_container()
The following example shows how to delete all containers that start with a specified prefix:
def delete_container_prefix(self, blob_service_client: BlobServiceClient):
container_list = list(blob_service_client.list_containers(name_starts_with="test-"))
assert len(container_list) >= 1
for container in container_list:
# Find containers with the specified prefix and delete
container_client = blob_service_client.get_container_client(container=container.name)
container_client.delete_container()
Restore a deleted container
When container soft delete is enabled for a storage account, a deleted container and its contents may be recovered within a specified retention period. To learn more about container soft delete, see Enable and manage soft delete for containers. You can restore a soft-deleted container by calling the following method of the BlobServiceClient
class:
The following example finds a deleted container, gets the version of that deleted container, and then passes the version into the undelete_container
method to restore the container.
def restore_deleted_container(self, blob_service_client: BlobServiceClient, container_name):
container_list = list(
blob_service_client.list_containers(include_deleted=True))
assert len(container_list) >= 1
for container in container_list:
# Find the deleted container and restore it
if container.deleted and container.name == container_name:
restored_container_client = blob_service_client.undelete_container(
deleted_container_name=container.name, deleted_container_version=container.version)
Delete a container asynchronously
The Azure Blob Storage client library for Python supports deleting a blob container asynchronously. To learn more about project setup requirements, see Asynchronous programming.
Follow these steps to delete a container using asynchronous APIs:
Add the following import statements:
import asyncio from azure.identity.aio import DefaultAzureCredential from azure.storage.blob.aio import BlobServiceClient
Add code to run the program using
asyncio.run
. This function runs the passed coroutine,main()
in our example, and manages theasyncio
event loop. Coroutines are declared with the async/await syntax. In this example, themain()
coroutine first creates the top levelBlobServiceClient
usingasync with
, then calls the method that deletes the container. Note that only the top level client needs to useasync 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.delete_container(blob_service_client, "sample-container") if __name__ == '__main__': asyncio.run(main())
Add code to delete the container. The code is the same as the synchronous example, except that the method is declared with the
async
keyword and theawait
keyword is used when calling thedelete_container
method.async def delete_container(self, blob_service_client: BlobServiceClient, container_name): container_client = blob_service_client.get_container_client(container=container_name) await container_client.delete_container()
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 deleting a container using the Azure Blob Storage client library for Python, see the following resources.
Code samples
- View synchronous or asynchronous code samples from this article (GitHub)
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 deleting or restoring a container use the following REST API operations:
- Delete Container (REST API)
- Restore Container (REST API)
Client library resources
See also
Related content
- 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.