ContainerClient class

Definition

A client to interact with a specific container, although that container may not yet exist.

For operations relating to a specific blob within this container, a blob client can be retrieved using the get_blob_client(blob, snapshot=None) function.

ContainerClient(account_url, container_name, credential=None, **kwargs)
Inheritance
builtins.object
azure.storage.blob._shared.base_client_async.AsyncStorageAccountHostsMixin
ContainerClient
azure.storage.blob._shared.base_client.StorageAccountHostsMixin
azure.storage.blob._container_client.ContainerClient
ContainerClient

Parameters

account_url
str

The URI to the storage account. In order to create a client given the full URI to the container, use the <xref:azure.storage.blob.aio.from_container_url> classmethod.

container_name
str

The name of the container for the blob.

credential

The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the URL already has a SAS token, specifying an explicit credential will take priority.

Examples

Get a ContainerClient from an existing BlobServiceClient.


   # Instantiate a BlobServiceClient using a connection string
   from azure.storage.blob.aio import BlobServiceClient
   blob_service_client = BlobServiceClient.from_connection_string(self.connection_string)

   # Instantiate a ContainerClient
   container_client = blob_service_client.get_container_client("mynewcontainerasync")

Creating the container client directly.


   from azure.storage.blob.aio import ContainerClient

   sas_url = sas_url = "https://account.blob.core.windows.net/mycontainer?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D"
   container = ContainerClient.from_container_url(sas_url)

Methods

acquire_lease(lease_duration=-1, lease_id=None, **kwargs)

Requests a new lease. If the container does not have an active lease, the Blob service creates a lease on the container and returns a new lease ID.

create_container(metadata=None, public_access=None, **kwargs)

Creates a new container under the specified account. If the container with the same name already exists, the operation fails.

delete_blob(blob, delete_snapshots=None, **kwargs)

Marks the specified blob or snapshot for deletion.

The blob is later deleted during garbage collection. Note that in order to delete a blob, you must delete all of its snapshots. You can delete both at the same time with the delete_blob operation.

If a delete retention policy is enabled for the service, then this operation soft deletes the blob or snapshot and retains the blob or snapshot for specified number of days. After specified number of days, blob's data is removed from the service during garbage collection. Soft deleted blob or snapshot is accessible through <xref:azure.storage.blob.aio.list_blobs> specifying include=["deleted"] option. Soft-deleted blob or snapshot can be restored using <xref:BlobClient.undelete>

delete_blobs(*blobs: typing.Union[str, azure.storage.blob._models.BlobProperties], delete_snapshots: typing.Union[str, NoneType] = None, lease: typing.Union[str, azure.storage.blob.aio._lease_async.BlobLeaseClient, NoneType] = None, **kwargs) -> typing.AsyncIterator[azure.core.pipeline.transport._base_async.AsyncHttpResponse]

Marks the specified blobs or snapshots for deletion.

The blobs are later deleted during garbage collection. Note that in order to delete blobs, you must delete all of their snapshots. You can delete both at the same time with the delete_blobs operation.

If a delete retention policy is enabled for the service, then this operation soft deletes the blobs or snapshots and retains the blobs or snapshots for specified number of days. After specified number of days, blobs' data is removed from the service during garbage collection. Soft deleted blobs or snapshots are accessible through <xref:azure.storage.blob.aio.list_blobs> specifying include=["deleted"] Soft-deleted blobs or snapshots can be restored using <xref:BlobClient.undelete>

delete_container(**kwargs)

Marks the specified container for deletion. The container and any blobs contained within it are later deleted during garbage collection.

download_blob(blob, offset=None, length=None, **kwargs)

Downloads a blob to the StorageStreamDownloader. The readall() method must be used to read all the content or readinto() must be used to download the blob into a stream.

get_account_information(**kwargs)

Gets information related to the storage account.

The information can also be retrieved if the user has a SAS to a container or blob. The keys in the returned dictionary include 'sku_name' and 'account_kind'.

get_blob_client(blob, snapshot=None)

Get a client to interact with the specified blob.

The blob need not already exist.

get_container_access_policy(**kwargs)

Gets the permissions for the specified container. The permissions indicate whether container data may be accessed publicly.

get_container_properties(**kwargs)

Returns all user-defined metadata and system properties for the specified container. The data returned does not include the container's list of blobs.

list_blobs(name_starts_with=None, include=None, **kwargs)

Returns a generator to list the blobs under the specified container. The generator will lazily follow the continuation tokens returned by the service.

set_container_access_policy(signed_identifiers, public_access=None, **kwargs)

Sets the permissions for the specified container or stored access policies that may be used with Shared Access Signatures. The permissions indicate whether blobs in a container may be accessed publicly.

set_container_metadata(metadata=None, **kwargs)

Sets one or more user-defined name-value pairs for the specified container. Each call to this operation replaces all existing metadata attached to the container. To remove all metadata from the container, call this operation with no metadata dict.

set_premium_page_blob_tier_blobs

Sets the page blob tiers on the blobs. This API is only supported for page blobs on premium accounts.

set_standard_blob_tier_blobs

This operation sets the tier on block blobs.

A block blob's tier determines Hot/Cool/Archive storage type. This operation does not update the blob's ETag.

upload_blob(name, data, blob_type=<BlobType.BlockBlob: 'BlockBlob'>, length=None, metadata=None, **kwargs)

Creates a new blob from a data source with automatic chunking.

walk_blobs(name_starts_with=None, include=None, delimiter='/', **kwargs)

Returns a generator to list the blobs under the specified container. The generator will lazily follow the continuation tokens returned by the service. This operation will list blobs in accordance with a hierarchy, as delimited by the specified delimiter character.

acquire_lease(lease_duration=-1, lease_id=None, **kwargs)

Requests a new lease. If the container does not have an active lease, the Blob service creates a lease on the container and returns a new lease ID.

acquire_lease(lease_duration=-1, lease_id=None, **kwargs)

Parameters

lease_duration
int

Specifies the duration of the lease, in seconds, or negative one (-1) for a lease that never expires. A non-infinite lease can be between 15 and 60 seconds. A lease duration cannot be changed using renew or change. Default is -1 (infinite lease).

lease_id
str

Proposed lease ID, in a GUID string format. The Blob service returns 400 (Invalid request) if the proposed lease ID is not in the correct format.

Returns

A BlobLeaseClient object, that can be run in a context manager.

Return type

Examples

Acquiring a lease on the container.


   # Acquire a lease on the container
   lease = await container_client.acquire_lease()

   # Delete container by passing in the lease
   await container_client.delete_container(lease=lease)

create_container(metadata=None, public_access=None, **kwargs)

Creates a new container under the specified account. If the container with the same name already exists, the operation fails.

create_container(metadata=None, public_access=None, **kwargs)

Parameters

metadata
dict[str, str]

A dict with name_value pairs to associate with the container as metadata. Example:{'Category':'test'}

public_access
PublicAccess

Possible values include: 'container', 'blob'.

Return type

Examples

Creating a container to store blobs.


   await container_client.create_container()

delete_blob(blob, delete_snapshots=None, **kwargs)

Marks the specified blob or snapshot for deletion.

The blob is later deleted during garbage collection. Note that in order to delete a blob, you must delete all of its snapshots. You can delete both at the same time with the delete_blob operation.

If a delete retention policy is enabled for the service, then this operation soft deletes the blob or snapshot and retains the blob or snapshot for specified number of days. After specified number of days, blob's data is removed from the service during garbage collection. Soft deleted blob or snapshot is accessible through <xref:azure.storage.blob.aio.list_blobs> specifying include=["deleted"] option. Soft-deleted blob or snapshot can be restored using <xref:BlobClient.undelete>

delete_blob(blob, delete_snapshots=None, **kwargs)

Parameters

blob
str or BlobProperties

The blob with which to interact. If specified, this value will override a blob value specified in the blob URL.

delete_snapshots
str

Required if the blob has associated snapshots. Values include:

  • "only": Deletes only the blobs snapshots.

  • "include": Deletes the blob along with all snapshots.

Return type

delete_blobs(*blobs: typing.Union[str, azure.storage.blob._models.BlobProperties], delete_snapshots: typing.Union[str, NoneType] = None, lease: typing.Union[str, azure.storage.blob.aio._lease_async.BlobLeaseClient, NoneType] = None, **kwargs) -> typing.AsyncIterator[azure.core.pipeline.transport._base_async.AsyncHttpResponse]

Marks the specified blobs or snapshots for deletion.

The blobs are later deleted during garbage collection. Note that in order to delete blobs, you must delete all of their snapshots. You can delete both at the same time with the delete_blobs operation.

If a delete retention policy is enabled for the service, then this operation soft deletes the blobs or snapshots and retains the blobs or snapshots for specified number of days. After specified number of days, blobs' data is removed from the service during garbage collection. Soft deleted blobs or snapshots are accessible through <xref:azure.storage.blob.aio.list_blobs> specifying include=["deleted"] Soft-deleted blobs or snapshots can be restored using <xref:BlobClient.undelete>

delete_blobs(*blobs: typing.Union[str, azure.storage.blob._models.BlobProperties], delete_snapshots: typing.Union[str, NoneType] = None, lease: typing.Union[str, azure.storage.blob.aio._lease_async.BlobLeaseClient, NoneType] = None, **kwargs) -> typing.AsyncIterator[azure.core.pipeline.transport._base_async.AsyncHttpResponse]

Parameters

blobs
str or BlobProperties

The blob names with which to interact. This can be a single blob, or multiple values can be supplied, where each value is either the name of the blob (str) or BlobProperties.

delete_snapshots
str

Required if a blob has associated snapshots. Values include:

  • "only": Deletes only the blobs snapshots.

  • "include": Deletes the blob along with all snapshots.

lease
BlobLeaseClient or str

Required if a blob has an active lease. Value can be a BlobLeaseClient object or the lease ID as a string.

Returns

An async iterator of responses, one for each blob in order

Return type

asynciterator[AsyncHttpResponse]

Examples

Deleting multiple blobs.


   # Delete multiple blobs in the container by name
   await container_client.delete_blobs("my_blob1", "my_blob2")

   # Delete multiple blobs by properties iterator
   my_blobs = container_client.list_blobs(name_starts_with="my_blob")
   await container_client.delete_blobs(*[b async for b in my_blobs])  # async for in list comprehension after 3.6 only

delete_container(**kwargs)

Marks the specified container for deletion. The container and any blobs contained within it are later deleted during garbage collection.

delete_container(**kwargs)

Return type

Examples

Delete a container.


   await container_client.delete_container()

download_blob(blob, offset=None, length=None, **kwargs)

Downloads a blob to the StorageStreamDownloader. The readall() method must be used to read all the content or readinto() must be used to download the blob into a stream.

download_blob(blob, offset=None, length=None, **kwargs)

Parameters

blob
str or BlobProperties

The blob with which to interact. If specified, this value will override a blob value specified in the blob URL.

offset
int

Start of byte range to use for downloading a section of the blob. Must be set if length is provided.

length
int

Number of bytes to read from the stream. This is optional, but should be supplied for optimal performance.

Returns

A streaming object. (StorageStreamDownloader)

Return type

get_account_information(**kwargs)

Gets information related to the storage account.

The information can also be retrieved if the user has a SAS to a container or blob. The keys in the returned dictionary include 'sku_name' and 'account_kind'.

get_account_information(**kwargs)

Returns

A dict of account information (SKU and account type).

Return type

get_blob_client(blob, snapshot=None)

Get a client to interact with the specified blob.

The blob need not already exist.

get_blob_client(blob, snapshot=None)

Parameters

blob
str or BlobProperties

The blob with which to interact.

snapshot
str

The optional blob snapshot on which to operate. This can be the snapshot ID string or the response returned from <xref:BlobClient.create_snapshot>.

default value: None

Returns

A BlobClient.

Return type

Examples

Get the blob client.


   # Get the BlobClient from the ContainerClient to interact with a specific blob
   blob_client = container_client.get_blob_client("mynewblob")

get_container_access_policy(**kwargs)

Gets the permissions for the specified container. The permissions indicate whether container data may be accessed publicly.

get_container_access_policy(**kwargs)

Returns

Access policy information in a dict.

Return type

dict[str, Any]

Examples

Getting the access policy on the container.


   policy = await container_client.get_container_access_policy()

get_container_properties(**kwargs)

Returns all user-defined metadata and system properties for the specified container. The data returned does not include the container's list of blobs.

get_container_properties(**kwargs)

Returns

Properties for the specified container within a container object.

Return type

Examples

Getting properties on the container.


   properties = await container_client.get_container_properties()

list_blobs(name_starts_with=None, include=None, **kwargs)

Returns a generator to list the blobs under the specified container. The generator will lazily follow the continuation tokens returned by the service.

list_blobs(name_starts_with=None, include=None, **kwargs)

Parameters

name_starts_with
str

Filters the results to return only blobs whose names begin with the specified prefix.

include
list[str]

Specifies one or more additional datasets to include in the response. Options include: 'snapshots', 'metadata', 'uncommittedblobs', 'copy', 'deleted'.

Returns

An iterable (auto-paging) response of BlobProperties.

Return type

Examples

List the blobs in the container.


   blobs_list = []
   async for blob in container_client.list_blobs():
       blobs_list.append(blob)

set_container_access_policy(signed_identifiers, public_access=None, **kwargs)

Sets the permissions for the specified container or stored access policies that may be used with Shared Access Signatures. The permissions indicate whether blobs in a container may be accessed publicly.

set_container_access_policy(signed_identifiers, public_access=None, **kwargs)

Parameters

signed_identifiers
dict[str, AccessPolicy]

A dictionary of access policies to associate with the container. The dictionary may contain up to 5 elements. An empty dictionary will clear the access policies set on the service.

public_access
PublicAccess

Possible values include: 'container', 'blob'.

Returns

Container-updated property dict (Etag and last modified).

Return type

Examples

Setting access policy on the container.


   # Create access policy
   from azure.storage.blob import AccessPolicy, ContainerSasPermissions
   access_policy = AccessPolicy(permission=ContainerSasPermissions(read=True),
                               expiry=datetime.utcnow() + timedelta(hours=1),
                               start=datetime.utcnow() - timedelta(minutes=1))

   identifiers = {'test': access_policy}

   # Set the access policy on the container
   await container_client.set_container_access_policy(signed_identifiers=identifiers)

set_container_metadata(metadata=None, **kwargs)

Sets one or more user-defined name-value pairs for the specified container. Each call to this operation replaces all existing metadata attached to the container. To remove all metadata from the container, call this operation with no metadata dict.

set_container_metadata(metadata=None, **kwargs)

Parameters

metadata
dict[str, str]

A dict containing name-value pairs to associate with the container as metadata. Example: {'category':'test'}

Returns

Container-updated property dict (Etag and last modified).

Examples

Setting metadata on the container.


   # Create key, value pairs for metadata
   metadata = {'type': 'test'}

   # Set metadata on the container
   await container_client.set_container_metadata(metadata=metadata)

set_premium_page_blob_tier_blobs

Sets the page blob tiers on the blobs. This API is only supported for page blobs on premium accounts.

Parameters

premium_page_blob_tier
PremiumPageBlobTier

A page blob tier value to set the blob to. The tier correlates to the size of the blob and number of allowed IOPS. This is only applicable to page blobs on premium storage accounts.

blobs
str or BlobProperties

The blobs with which to interact. This can be a single blob, or multiple values can be supplied, where each value is either the name of the blob (str) or BlobProperties.

Returns

An async iterator of responses, one for each blob in order

Return type

asynciterator[AsyncHttpResponse]

set_standard_blob_tier_blobs

This operation sets the tier on block blobs.

A block blob's tier determines Hot/Cool/Archive storage type. This operation does not update the blob's ETag.

Parameters

standard_blob_tier
str or StandardBlobTier

Indicates the tier to be set on the blob. Options include 'Hot', 'Cool', 'Archive'. The hot tier is optimized for storing data that is accessed frequently. The cool storage tier is optimized for storing data that is infrequently accessed and stored for at least a month. The archive tier is optimized for storing data that is rarely accessed and stored for at least six months with flexible latency requirements.

blobs
str or BlobProperties

The blobs with which to interact. This can be a single blob, or multiple values can be supplied, where each value is either the name of the blob (str) or BlobProperties.

Returns

An async iterator of responses, one for each blob in order

Return type

asynciterator[AsyncHttpResponse]

upload_blob(name, data, blob_type=<BlobType.BlockBlob: 'BlockBlob'>, length=None, metadata=None, **kwargs)

Creates a new blob from a data source with automatic chunking.

upload_blob(name, data, blob_type=<BlobType.BlockBlob: 'BlockBlob'>, length=None, metadata=None, **kwargs)

Parameters

name
str or BlobProperties

The blob with which to interact. If specified, this value will override a blob value specified in the blob URL.

data

The blob data to upload.

blob_type
BlobType

The type of the blob. This can be either BlockBlob, PageBlob or AppendBlob. The default value is BlockBlob.

length
int

Number of bytes to read from the stream. This is optional, but should be supplied for optimal performance.

metadata
dict(str, str)

Name-value pairs associated with the blob as metadata.

Returns

A BlobClient to interact with the newly uploaded blob.

Return type

Examples

Upload blob to the container.


   with open(SOURCE_FILE, "rb") as data:
       blob_client = await container_client.upload_blob(name="myblob", data=data)

   properties = await blob_client.get_blob_properties()

walk_blobs(name_starts_with=None, include=None, delimiter='/', **kwargs)

Returns a generator to list the blobs under the specified container. The generator will lazily follow the continuation tokens returned by the service. This operation will list blobs in accordance with a hierarchy, as delimited by the specified delimiter character.

walk_blobs(name_starts_with=None, include=None, delimiter='/', **kwargs)

Parameters

name_starts_with
str

Filters the results to return only blobs whose names begin with the specified prefix.

include
list[str]

Specifies one or more additional datasets to include in the response. Options include: 'snapshots', 'metadata', 'uncommittedblobs', 'copy', 'deleted'.

delimiter
str

When the request includes this parameter, the operation returns a BlobPrefix element in the response body that acts as a placeholder for all blobs whose names begin with the same substring up to the appearance of the delimiter character. The delimiter may be a single character or a string.

Returns

An iterable (auto-paging) response of BlobProperties.

Return type