Delete and restore a blob with Python

This article shows how to delete blobs using the Azure Storage client library for Python, and how to restore soft-deleted blobs during the retention period.

To learn about deleting a blob using asynchronous APIs, see Delete a blob 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 delete a blob, or to restore a soft-deleted blob. 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 Blob (REST API) and Undelete Blob (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.chinacloudapi.cn"
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 blob

Note

When blob soft delete is enabled for a storage account, you can't perform a permanent deletion using client library methods. Using the methods in this article, a soft-deleted blob, blob version, or snapshot remains available until the retention period expires, at which time it's permanently deleted. To learn more about the underlying REST API operation, see Delete Blob (REST API).

To delete a blob, call the following method:

The following example deletes a blob:

def delete_blob(self, blob_service_client: BlobServiceClient, container_name: str, blob_name: str):
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
    blob_client.delete_blob()

If the blob has any associated snapshots, you must delete all of its snapshots to delete the blob. The following example deletes a blob and its snapshots:

def delete_blob_snapshots(self, blob_service_client: BlobServiceClient, container_name: str, blob_name: str):
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
    blob_client.delete_blob(delete_snapshots="include")

To delete only the snapshots and not the blob itself, you can pass the parameter delete_snapshots="only".

Restore a deleted blob

Blob soft delete protects an individual blob and its versions, snapshots, and metadata from accidental deletes or overwrites by maintaining the deleted data in the system for a specified period of time. During the retention period, you can restore the blob to its state at deletion. After the retention period has expired, the blob is permanently deleted. For more information about blob soft delete, see Soft delete for blobs.

You can use the Azure Storage client libraries to restore a soft-deleted blob or snapshot.

How you restore a soft-deleted blob depends on whether or not your storage account has blob versioning enabled. For more information on blob versioning, see Blob versioning. See one of the following sections, depending on your scenario:

Restore soft-deleted objects when versioning is disabled

To restore deleted blobs when versioning is disabled, call the following method:

This method restores the content and metadata of a soft-deleted blob and any associated soft-deleted snapshots. Calling this method for a blob that hasn't been deleted has no effect.

def restore_blob(self, blob_service_client: BlobServiceClient, container_name: str, blob_name: str):
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
    blob_client.undelete_blob()

Restore soft-deleted objects when versioning is enabled

If a storage account is configured to enable blob versioning, deleting a blob causes the current version of the blob to become the previous version. To restore a soft-deleted blob when versioning is enabled, copy a previous version over the base blob. You can use the following method:

The following code example gets the latest version of a deleted blob, and restores the latest version by copying it to the base blob:

def restore_blob_version(self, blob_service_client: BlobServiceClient, container_name: str, blob_name: str):
    container_client = blob_service_client.get_container_client(container=container_name)

    # Get a reference to the soft-deleted base blob and list all the blob versions
    blob_client = container_client.get_blob_client(blob=blob_name)
    blob_list = container_client.list_blobs(name_starts_with=blob_name, include=['deleted','versions'])
    blob_versions = []
    for blob in blob_list:
        blob_versions.append(blob.version_id)
    
    # Get the latest version of the soft-deleted blob
    blob_versions.sort(reverse=True)
    latest_version = blob_versions[0]

    # Build the blob URI and add the version ID as a query string
    versioned_blob_url = f"{blob_client.url}?versionId={latest_version}"

    # Restore the latest version by copying it to the base blob
    blob_client.start_copy_from_url(versioned_blob_url)

Delete a blob asynchronously

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

Follow these steps to delete a blob using asynchronous APIs:

  1. Add the following import statements:
import asyncio

from azure.identity.aio import DefaultAzureCredential
from azure.storage.blob.aio import BlobServiceClient
  1. 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 deletes the blob. 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 = BlobSamples()

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

    async with BlobServiceClient(account_url, credential=credential) as blob_service_client:
        await sample.delete_blob(blob_service_client, "sample-container", "sample-blob.txt")

if __name__ == '__main__':
    asyncio.run(main())
  1. Add code to delete the blob. 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 delete_blob method.
async def delete_blob(self, blob_service_client: BlobServiceClient, container_name: str, blob_name: str):
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
    await blob_client.delete_blob()

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 how to delete blobs and restore deleted blobs 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 deleting blobs and restoring deleted blobs use the following REST API operations:

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.