Create and manage container leases with Python
This article shows how to create and manage container leases using the Azure Storage client library for Python. You can use the client library to acquire, renew, release and break container leases.
To learn about leasing a blob container using asynchronous APIs, see Lease containers 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, BlobLeaseClient
Authorization
The authorization mechanism must have the necessary permissions to work with a container lease. 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 Lease 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.
About container leases
A lease establishes and manages a lock on a container for delete operations. The lock duration can be 15 to 60 seconds, or can be infinite. A lease on a container provides exclusive delete access to the container. A container lease only controls the ability to delete the container using the Delete Container REST API operation. To delete a container with an active lease, a client must include the active lease ID with the delete request. All other container operations succeed on a leased container without the lease ID. If you've enabled container soft delete, you can restore deleted containers.
To learn more about lease states and when you can perform a given action on a lease, see Lease states and actions.
Lease operations are handled by the BlobLeaseClient class, which provides a client containing all lease operations for blobs and containers. To learn more about blob leases using the client library, see Create and manage blob leases with Python.
Acquire a lease
When you acquire a container lease, you obtain a lease ID that your code can use to operate on the container. If the container 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 the BlobLeaseClient class, and then use the following method:
You can also acquire a lease using the following method from the ContainerClient class:
The following example acquires a 30-second lease on a container:
def acquire_container_lease(self, blob_service_client: BlobServiceClient, container_name):
# Instantiate a ContainerClient
container_client = blob_service_client.get_container_client(container=container_name)
# Acquire a 30-second lease on the container
lease_client = container_client.acquire_lease(30)
return lease_client
Renew a lease
You can renew a container lease if the lease ID specified on the request matches the lease ID associated with the container. The lease can be renewed even if it has expired, as long as the container hasn't been 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 container:
def renew_container_lease(self, lease_client: BlobLeaseClient):
# Renew a lease on the container
lease_client.renew()
Release a lease
You can release a container lease if the lease ID specified on the request matches the lease ID associated with the container. Releasing a lease allows another client to acquire a lease for the container immediately after the release is complete.
You can release a lease by using the following method:
The following example releases the lease on a container:
def release_container_lease(self, lease_client: BlobLeaseClient):
# Release a lease on the container
lease_client.release()
Break a lease
You can break a container lease if the container 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 container:
def break_container_lease(self, lease_client: BlobLeaseClient):
# Break a lease on the container
lease_client.break_lease()
Lease containers asynchronously
The Azure Blob Storage client library for Python supports leasing containers asynchronously. To learn more about project setup requirements, see Asynchronous programming.
Follow these steps to lease 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, BlobLeaseClient
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 acquires the container 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 = 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: lease_client = await sample.acquire_container_lease(blob_service_client, "sample-container") if __name__ == '__main__': asyncio.run(main())
Add code to acquire a container lease. 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 theacquire
method.async def acquire_container_lease(self, blob_service_client: BlobServiceClient, container_name): # Instantiate a ContainerClient container_client = blob_service_client.get_container_client(container=container_name) # Acquire a 30-second lease on the container lease_client = BlobLeaseClient(container_client) await lease_client.acquire(lease_duration=30) return lease_client
With this basic setup in place, you can implement other examples in this article as coroutines using async/await syntax.
Lease states and actions
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 , and break |
Expired | The lease duration has expired. | acquire , renew , release , and break |
Breaking | The lease has been broken, but the lease will continue to be locked until the break period has expired. | release and break |
Broken | The lease has been broken, and the break period has expired. | acquire , release , and break |
When a lease expires, the lease ID is maintained by the Blob service until the container is modified or leased again. A client may attempt to renew or release the lease using the expired lease ID. If the request fails, the client knows that the container was leased again, or the container was deleted since the lease was last active.
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 container. However, the client can renew the lease with the expired lease ID immediately.
Resources
To learn more about leasing 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 leasing a container use the following REST API operation:
- Lease 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.