Delete and restore a blob with Python
This article shows how to delete blobs using the Azure Storage client library for Python. If you've enabled soft delete for blobs, you can restore deleted blobs during the retention period.
To learn about deleting a blob using asynchronous APIs, see Delete a blob asynchronously.
Prerequisites
- This article assumes you already have a project set up to work with the Azure Blob Storage client library for Python. To learn about setting up your project, including package installation, adding
import
statements, and creating an authorized client object, see Get started with Azure Blob Storage and Python. - To use asynchronous APIs in your code, see the requirements in the Asynchronous programming section.
- The authorization mechanism must have permissions to delete a blob, or to restore a soft-deleted blob. To learn more, see the authorization guidance for the following REST API operations:
Delete a blob
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:
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 blob. 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 = BlobSamples() # 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_blob(blob_service_client, "sample-container", "sample-blob.txt") if __name__ == '__main__': asyncio.run(main())
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 theawait
keyword is used when calling thedelete_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.
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:
- Delete Blob (REST API)
- Undelete Blob (REST API)
Code samples
- View synchronous or asynchronous code samples from this article (GitHub)
Client library resources
See also
Feedback
https://aka.ms/ContentUserFeedback.
Disponibbli dalwaqt: Matul l-2024 se nkunu qed inwaqqfu gradwalment Problemi GitHub bħala l-mekkaniżmu ta’ feedback għall-kontenut u se nibdluh b’sistema ġdida ta’ feedback. Għal aktar informazzjoni, ara:Issottometti u ara feedback għal