This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
This article shows how to create and manage blob leases using theAzure Storage client library for Python. You can use the client library to acquire, renew, release, and break blob leases.
To learn about leasing a blob using asynchronous APIs, seeLease blobs asynchronously.
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, seeGet 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 the following packages usingpip install:
pip install azure-storage-blob azure-identityAdd the followingimport statements:
from azure.identity import DefaultAzureCredentialfrom azure.storage.blob import BlobServiceClient, BlobLeaseClientThe authorization mechanism must have the necessary permissions to work with a blob lease. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in roleStorage Blob Data Contributor or higher. To learn more, see the authorization guidance forLease Blob (REST API).
To connect an app to Blob Storage, create an instance ofBlobServiceClient. The following example shows how to create a client object usingDefaultAzureCredential for authorization:
# TODO: Replace <storage-account-name> with your actual storage account nameaccount_url = "https://<storage-account-name>.blob.core.windows.net"credential = DefaultAzureCredential()# Create the BlobServiceClient objectblob_service_client = BlobServiceClient(account_url, credential=credential)You can also create client objects for specificcontainers orblobs, either directly or from theBlobServiceClient object. To learn more about creating and managing client objects, seeCreate and manage client objects that interact with data resources.
A lease creates and manages a lock on a blob for write and delete operations. The lock duration can be 15 to 60 seconds, or can be infinite. A lease on a blob provides exclusive write and delete access to the blob. To write to a blob with an active lease, a client must include the active lease ID with the write request.
To learn more about lease states and when you can perform a given action on a lease, seeLease states and actions.
All container operations are permitted on a container that includes blobs with an active lease, includingDelete Container. Therefore, a container may be deleted even if blobs within it have active leases. Use theLease Container operation to control rights to delete a container.
Lease operations are handled by theBlobLeaseClient class, which provides a client containing all lease operations for blobs and containers. To learn more about container leases using the client library, seeCreate and manage container leases with Python.
When you acquire a blob lease, you obtain a lease ID that your code can use to operate on the blob. If the blob already has an active lease, you can only request a new lease by using the active lease ID. However, you can specify a new lease duration.
To acquire a lease, create an instance of theBlobLeaseClient class, and then use the following method:
You can also acquire a lease on a blob by creating an instance ofBlobClient, and using the following method:
The following example acquires a 30-second lease for a blob:
def acquire_blob_lease(self, blob_service_client: BlobServiceClient, container_name): # Instantiate a BlobClient blob_client = blob_service_client.get_blob_client(container=container_name, blob="sample-blob.txt") # Acquire a 30-second lease on the blob lease_client = blob_client.acquire_lease(30) return lease_clientYou can renew a blob lease if the lease ID specified on the request matches the lease ID associated with the blob. The lease can be renewed even if it has expired, as long as the blob hasn't been modified or leased again since the expiration of that lease. When you renew a lease, the duration of the lease resets.
To renew a lease, use the following method:
The following example renews a lease for a blob:
def renew_blob_lease(self, lease_client: BlobLeaseClient): # Renew a lease on a blob lease_client.renew()You can release a blob lease if the lease ID specified on the request matches the lease ID associated with the blob. Releasing a lease allows another client to acquire a lease for the blob immediately after the release is complete.
You can release a lease by using the following method:
The following example releases the lease on a blob:
def release_blob_lease(self, lease_client: BlobLeaseClient): # Release a lease on a blob lease_client.release()You can break a blob lease if the blob has an active lease. Any authorized request can break the lease; the request isn't required to specify a matching lease ID. A lease can't be renewed after it's broken, and breaking a lease prevents a new lease from being acquired for a period of time until the original lease expires or is released.
You can break a lease by using the following method:
The following example breaks the lease on a blob:
def break_blob_lease(self, lease_client: BlobLeaseClient): # Break a lease on a blob lease_client.break_lease()The Azure Blob Storage client library for Python supports leasing blobs asynchronously. To learn more about project setup requirements, seeAsynchronous programming.
Follow these steps to lease a blob using asynchronous APIs:
Add the following import statements:
import asynciofrom azure.identity.aio import DefaultAzureCredentialfrom azure.storage.blob.aio import BlobServiceClient, BlobLeaseClientAdd code to run the program usingasyncio.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 acquires the blob lease. 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: lease_client = await sample.acquire_blob_lease(blob_service_client, "sample-container")if __name__ == '__main__': asyncio.run(main())Add code to acquire a blob lease. The code is the same as the synchronous example, except that the method is declared with theasync keyword and theawait keyword is used when calling theacquire_lease method.
async def acquire_blob_lease(self, blob_service_client: BlobServiceClient, container_name): # Instantiate a BlobClient blob_client = blob_service_client.get_blob_client(container=container_name, blob="sample-blob.txt") # Acquire a 30-second lease on the blob lease_client = await blob_client.acquire_lease(30) return lease_clientWith this basic setup in place, you can implement other examples in this article as coroutines using async/await syntax.
The following diagram shows the five states of a lease, and the commands or events that cause lease state changes.
The following table lists the five lease states, gives a brief description of each, and lists the lease actions allowed in a given state. These lease actions cause state transitions, as shown in the diagram.
| Lease state | Description | Lease actions allowed |
|---|---|---|
| Available | The lease is unlocked and can be acquired. | acquire |
| Leased | The lease is locked. | acquire (same lease ID only),renew,change,release, andbreak |
| Expired | The lease duration has expired. | acquire,renew,release, andbreak |
| Breaking | The lease has been broken, but the lease will continue to be locked until the break period has expired. | release andbreak |
| Broken | The lease has been broken, and the break period has expired. | acquire,release, andbreak |
When a lease expires, the lease ID is maintained by the Blob service until the blob is modified or leased again. A client may attempt to renew or release the lease using the expired lease ID. If this operation is successful, the client knows that the blob hasn't been changed since the lease ID was last valid. If the request fails, the client knows that the blob was modified, or the blob was leased again since the lease was last active. The client must then acquire a new lease on the blob.
If a lease expires rather than being explicitly released, a client may need to wait up to one minute before a new lease can be acquired for the blob. However, the client can renew the lease with their lease ID immediately if the blob hasn't been modified.
A lease can't be granted for a blob snapshot, since snapshots are read-only. Requesting a lease against a snapshot results in status code400 (Bad Request).
To learn more about managing blob leases using the Azure Blob Storage client library for Python, see the following resources.
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 managing blob leases use the following REST API operation:
Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?