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.StorageAccountHostsMixin
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 from_container_url(container_url, credential=None, **kwargs) 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 import BlobServiceClient
   blob_service_client = BlobServiceClient.from_connection_string(self.connection_string)

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

Creating the container client directly.


   from azure.storage.blob import ContainerClient

   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

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

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

delete_blob

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.list_blobs> specifying include=["deleted"] option. Soft-deleted blob or snapshot can be restored using <xref:BlobClient.undelete>

delete_blobs

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.list_blobs> specifying include=["deleted"] Soft-deleted blobs or snapshots can be restored using <xref:BlobClient.undelete>

delete_container

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

download_blob

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.

from_connection_string

Create ContainerClient from a Connection String.

from_container_url

Create ContainerClient from a container url.

get_account_information

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

Get a client to interact with the specified blob.

The blob need not already exist.

get_container_access_policy

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

get_container_properties

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

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

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

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

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

walk_blobs

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

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
Required

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
Required

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 = container_client.acquire_lease()

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

create_container

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]
Required

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

public_access
PublicAccess
Required

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

Return type

None

Examples

Creating a container to store blobs.


   container_client.create_container()

delete_blob

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.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
Required

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

delete_snapshots
str
Required

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

None

delete_blobs

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.list_blobs> specifying include=["deleted"] Soft-deleted blobs or snapshots can be restored using <xref:BlobClient.undelete>

delete_blobs(*blobs, **kwargs)

Parameters

blobs
str or BlobProperties
Required

The blobs to delete. 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 iterator of responses, one for each blob in order

Return type

Iterator[HttpResponse]

Examples

Deleting multiple blobs.


   # Delete multiple blobs in the container by name
   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")
   container_client.delete_blobs(*my_blobs)

delete_container

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

None

Examples

Delete a container.


   container_client.delete_container()

download_blob

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
Required

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

offset
int
Required

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

length
int
Required

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

from_connection_string

Create ContainerClient from a Connection String.

from_connection_string(conn_str, container_name, credential=None, **kwargs)

Parameters

conn_str
str
Required

A connection string to an Azure Storage account.

container_name
str
Required

The container name for the blob.

credential
Required

The credentials with which to authenticate. This is optional if the account URL already has a SAS token, or the connection string already has shared access key values. The value can be a SAS token string, an account shared access key, or an instance of a TokenCredentials class from azure.identity. Credentials provided here will take precedence over those in the connection string.

credential
default value: None

Returns

A container client.

Return type

Examples

Creating the ContainerClient from a connection string.


   from azure.storage.blob import ContainerClient
   container_client = ContainerClient.from_connection_string(
       self.connection_string, container_name="mycontainer")

from_container_url

Create ContainerClient from a container url.

from_container_url(container_url, credential=None, **kwargs)

Parameters

container_url
str
Required

The full endpoint URL to the Container, including SAS token if used. This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode.

credential
Required

The credentials with which to authenticate. This is optional if the account URL already has a SAS token, or the connection string already has shared access key values. The value can be a SAS token string, an account shared access key, or an instance of a TokenCredentials class from azure.identity. Credentials provided here will take precedence over those in the connection string.

credential
default value: None

Returns

A container client.

Return type

get_account_information

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

dict(str, str)

get_blob_client

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
Required

The blob with which to interact.

snapshot
str
default value: None

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

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

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 = container_client.get_container_access_policy()

get_container_properties

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 = container_client.get_container_properties()

list_blobs

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
Required

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

include
list[str]
Required

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 = container_client.list_blobs()
   for blob in blobs_list:
       print(blob.name + '\n')

set_container_access_policy

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]
Required

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
Required

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

Returns

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

Return type

dict[str, str
datetime.datetime]

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
   container_client.set_container_access_policy(signed_identifiers=identifiers)

set_container_metadata

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]
Required

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).

Return type

dict[str, str
datetime]

Examples

Setting metadata on the container.


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

   # Set metadata on the container
   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.

set_premium_page_blob_tier_blobs(premium_page_blob_tier, *blobs, **kwargs)

Parameters

premium_page_blob_tier
PremiumPageBlobTier
Required

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
Required

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 iterator of responses, one for each blob in order

Return type

iterator[HttpResponse]

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.

set_standard_blob_tier_blobs(standard_blob_tier, *blobs, **kwargs)

Parameters

standard_blob_tier
str or StandardBlobTier
Required

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
Required

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 iterator of responses, one for each blob in order

Return type

Iterator[HttpResponse]

upload_blob

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
Required

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

data
Required

The blob data to upload.

blob_type
BlobType
Required

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

length
int
Required

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

metadata
dict(str, str)
Required

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 = container_client.upload_blob(name="myblob", data=data)

   properties = blob_client.get_blob_properties()

walk_blobs

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
Required

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

include
list[str]
Required

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

delimiter
str
Required

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