BlobServiceClient Class

A client to interact with the Blob Service at the account level.

This client provides operations to retrieve and configure the account properties as well as list, create and delete containers within the account. For operations relating to a specific container or blob, clients for those entities can also be retrieved using the get_client functions.

For more optional configuration, please click here.

Inheritance
azure.storage.blob._shared.base_client.StorageAccountHostsMixin
BlobServiceClient
azure.storage.blob._encryption.StorageEncryptionMixin
BlobServiceClient

Constructor

BlobServiceClient(account_url: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any)

Parameters

Name Description
account_url
Required
str

The URL to the blob storage account. Any other entities included in the URL path (e.g. container or blob) will be discarded. This URL can be optionally authenticated with a SAS token.

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 instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential

  • except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, "name" should be the storage account name, and "key" should be the storage account key.
Default value: None

Keyword-Only Parameters

Name Description
api_version
str

The Storage API version to use for requests. Default value is the most recent service version that is compatible with the current SDK. Setting to an older version may result in reduced feature compatibility.

New in version 12.2.0.

secondary_hostname
str

The hostname of the secondary endpoint.

max_block_size
int

The maximum chunk size for uploading a block blob in chunks. Defaults to 4*1024*1024, or 4MB.

max_single_put_size
int

If the blob size is less than or equal max_single_put_size, then the blob will be uploaded with only one http PUT request. If the blob size is larger than max_single_put_size, the blob will be uploaded in chunks. Defaults to 64*1024*1024, or 64MB.

min_large_block_upload_threshold
int

The minimum chunk size required to use the memory efficient algorithm when uploading a block blob. Defaults to 4*1024*1024+1.

use_byte_buffer

Use a byte buffer for block blob uploads. Defaults to False.

max_page_size
int

The maximum chunk size for uploading a page blob. Defaults to 4*1024*1024, or 4MB.

max_single_get_size
int

The maximum size for a blob to be downloaded in a single call, the exceeded part will be downloaded in chunks (could be parallel). Defaults to 32*1024*1024, or 32MB.

max_chunk_get_size
int

The maximum chunk size used for downloading a blob. Defaults to 4*1024*1024, or 4MB.

audience
str

The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://.blob.core.windows.net.

Methods

close

This method is to close the sockets opened by the client. It need not be used when using with a context manager.

create_container

Creates a new container under the specified account.

If the container with the same name already exists, a ResourceExistsError will be raised. This method returns a client with which to interact with the newly created container.

delete_container

Marks the specified container for deletion.

The container and any blobs contained within it are later deleted during garbage collection. If the container is not found, a ResourceNotFoundError will be raised.

find_blobs_by_tags

The Filter Blobs operation enables callers to list blobs across all containers whose tags match a given search expression. Filter blobs searches across all containers within a storage account but can be scoped within the expression to a single container.

from_connection_string

Create BlobServiceClient from a Connection String.

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_client

Get a client to interact with the specified container.

The container need not already exist.

get_service_properties

Gets the properties of a storage account's Blob service, including Azure Storage Analytics.

get_service_stats

Retrieves statistics related to replication for the Blob service.

It is only available when read-access geo-redundant replication is enabled for the storage account.

With geo-redundant replication, Azure Storage maintains your data durable in two locations. In both locations, Azure Storage constantly maintains multiple healthy replicas of your data. The location where you read, create, update, or delete data is the primary storage account location. The primary location exists in the region you choose at the time you create an account via the Azure Management Azure classic portal, for example, North Central US. The location to which your data is replicated is the secondary location. The secondary location is automatically determined based on the location of the primary; it is in a second data center that resides in the same region as the primary location. Read-only access is available from the secondary location, if read-access geo-redundant replication is enabled for your storage account.

get_user_delegation_key

Obtain a user delegation key for the purpose of signing SAS tokens. A token credential must be present on the service object for this request to succeed.

list_containers

Returns a generator to list the containers under the specified account.

The generator will lazily follow the continuation tokens returned by the service and stop when all containers have been returned.

set_service_properties

Sets the properties of a storage account's Blob service, including Azure Storage Analytics.

If an element (e.g. analytics_logging) is left as None, the existing settings on the service for that functionality are preserved.

undelete_container

Restores soft-deleted container.

Operation will only be successful if used within the specified number of days set in the delete retention policy.

New in version 12.4.0: This operation was introduced in API version '2019-12-12'.

close

This method is to close the sockets opened by the client. It need not be used when using with a context manager.

close()

create_container

Creates a new container under the specified account.

If the container with the same name already exists, a ResourceExistsError will be raised. This method returns a client with which to interact with the newly created container.

create_container(name: str, metadata: Dict[str, str] | None = None, public_access: PublicAccess | str | None = None, **kwargs: Any) -> ContainerClient

Parameters

Name Description
name
Required
str

The name of the container to create.

metadata
Required

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

public_access
Required

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

Keyword-Only Parameters

Name Description
container_encryption_scope

Specifies the default encryption scope to set on the container and use for all future writes.

New in version 12.2.0.

timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

A container client to interact with the newly created container.

delete_container

Marks the specified container for deletion.

The container and any blobs contained within it are later deleted during garbage collection. If the container is not found, a ResourceNotFoundError will be raised.

delete_container(container: ContainerProperties | str, lease: BlobLeaseClient | str | None = None, **kwargs: Any) -> None

Parameters

Name Description
container
Required

The container to delete. This can either be the name of the container, or an instance of ContainerProperties.

lease
Required

If specified, delete_container only succeeds if the container's lease is active and matches this ID. Required if the container has an active lease.

Keyword-Only Parameters

Name Description
if_modified_since

A DateTime value. Azure expects the date value passed in to be UTC. If timezone is included, any non-UTC datetimes will be converted to UTC. If a date is passed in without timezone info, it is assumed to be UTC. Specify this header to perform the operation only if the resource has been modified since the specified time.

if_unmodified_since

A DateTime value. Azure expects the date value passed in to be UTC. If timezone is included, any non-UTC datetimes will be converted to UTC. If a date is passed in without timezone info, it is assumed to be UTC. Specify this header to perform the operation only if the resource has not been modified since the specified date/time.

etag
str

An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

match_condition

The match condition to use upon the etag.

timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

find_blobs_by_tags

The Filter Blobs operation enables callers to list blobs across all containers whose tags match a given search expression. Filter blobs searches across all containers within a storage account but can be scoped within the expression to a single container.

find_blobs_by_tags(filter_expression: str, **kwargs: Any) -> ItemPaged[FilteredBlob]

Parameters

Name Description
filter_expression
Required
str

The expression to find blobs whose tags matches the specified condition. eg. ""yourtagname"='firsttag' and "yourtagname2"='secondtag'" To specify a container, eg. "@container='containerName' and "Name"='C'"

Keyword-Only Parameters

Name Description
results_per_page
int

The max result per page when paginating.

timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

An iterable (auto-paging) response of BlobProperties.

from_connection_string

Create BlobServiceClient from a Connection String.

from_connection_string(conn_str: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any) -> Self

Parameters

Name Description
conn_str
Required
str

A connection string to an Azure Storage account.

credential

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 instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, 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. If using an instance of AzureNamedKeyCredential, "name" should be the storage account name, and "key" should be the storage account key.

Default value: None

Keyword-Only Parameters

Name Description
audience
str

The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://.blob.core.windows.net.

Returns

Type Description

A Blob service client.

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: Any) -> Dict[str, str]

Returns

Type Description

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

get_blob_client

Get a client to interact with the specified blob.

The blob need not already exist.

get_blob_client(container: ContainerProperties | str, blob: str, snapshot: str | Dict[str, Any] | None = None, *, version_id: str | None = None) -> BlobClient

Parameters

Name Description
container
Required

The container that the blob is in. This can either be the name of the container, or an instance of ContainerProperties.

blob
Required
str

The name of the blob with which to interact.

snapshot
str or dict(str, Any)

The optional blob snapshot on which to operate. This can either be the ID of the snapshot, or a dictionary output returned by create_snapshot.

Default value: None

Keyword-Only Parameters

Name Description
version_id
str

The version id parameter is an opaque DateTime value that, when present, specifies the version of the blob to operate on.

Returns

Type Description

A BlobClient.

get_container_client

Get a client to interact with the specified container.

The container need not already exist.

get_container_client(container: ContainerProperties | str) -> ContainerClient

Parameters

Name Description
container
Required

The container. This can either be the name of the container, or an instance of ContainerProperties.

Returns

Type Description

A ContainerClient.

get_service_properties

Gets the properties of a storage account's Blob service, including Azure Storage Analytics.

get_service_properties(**kwargs: Any) -> Dict[str, Any]

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

An object containing blob service properties such as analytics logging, hour/minute metrics, cors rules, etc.

get_service_stats

Retrieves statistics related to replication for the Blob service.

It is only available when read-access geo-redundant replication is enabled for the storage account.

With geo-redundant replication, Azure Storage maintains your data durable in two locations. In both locations, Azure Storage constantly maintains multiple healthy replicas of your data. The location where you read, create, update, or delete data is the primary storage account location. The primary location exists in the region you choose at the time you create an account via the Azure Management Azure classic portal, for example, North Central US. The location to which your data is replicated is the secondary location. The secondary location is automatically determined based on the location of the primary; it is in a second data center that resides in the same region as the primary location. Read-only access is available from the secondary location, if read-access geo-redundant replication is enabled for your storage account.

get_service_stats(**kwargs: Any) -> Dict[str, Any]

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

The blob service stats.

get_user_delegation_key

Obtain a user delegation key for the purpose of signing SAS tokens. A token credential must be present on the service object for this request to succeed.

get_user_delegation_key(key_start_time: datetime, key_expiry_time: datetime, **kwargs: Any) -> UserDelegationKey

Parameters

Name Description
key_start_time
Required

A DateTime value. Indicates when the key becomes valid.

key_expiry_time
Required

A DateTime value. Indicates when the key stops being valid.

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

The user delegation key.

list_containers

Returns a generator to list the containers under the specified account.

The generator will lazily follow the continuation tokens returned by the service and stop when all containers have been returned.

list_containers(name_starts_with: str | None = None, include_metadata: bool = False, **kwargs: Any) -> ItemPaged[ContainerProperties]

Parameters

Name Description
name_starts_with
Required
str

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

include_metadata
Required

Specifies that container metadata to be returned in the response. The default value is False.

Keyword-Only Parameters

Name Description
include_deleted

Specifies that deleted containers to be returned in the response. This is for container restore enabled account. The default value is False. .. versionadded:: 12.4.0

include_system

Flag specifying that system containers should be included. .. versionadded:: 12.10.0

results_per_page
int

The maximum number of container names to retrieve per API call. If the request does not specify the server will return up to 5,000 items.

timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

An iterable (auto-paging) of ContainerProperties.

set_service_properties

Sets the properties of a storage account's Blob service, including Azure Storage Analytics.

If an element (e.g. analytics_logging) is left as None, the existing settings on the service for that functionality are preserved.

set_service_properties(analytics_logging: BlobAnalyticsLogging | None = None, hour_metrics: Metrics | None = None, minute_metrics: Metrics | None = None, cors: List[CorsRule] | None = None, target_version: str | None = None, delete_retention_policy: RetentionPolicy | None = None, static_website: StaticWebsite | None = None, **kwargs: Any) -> None

Parameters

Name Description
analytics_logging
Required

Groups the Azure Analytics Logging settings.

hour_metrics
Required

The hour metrics settings provide a summary of request statistics grouped by API in hourly aggregates for blobs.

minute_metrics
Required

The minute metrics settings provide request statistics for each minute for blobs.

cors
Required

You can include up to five CorsRule elements in the list. If an empty list is specified, all CORS rules will be deleted, and CORS will be disabled for the service.

target_version
Required
str

Indicates the default version to use for requests if an incoming request's version is not specified.

delete_retention_policy
Required

The delete retention policy specifies whether to retain deleted blobs. It also specifies the number of days and versions of blob to keep.

static_website
Required

Specifies whether the static website feature is enabled, and if yes, indicates the index document and 404 error document to use.

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

undelete_container

Restores soft-deleted container.

Operation will only be successful if used within the specified number of days set in the delete retention policy.

New in version 12.4.0: This operation was introduced in API version '2019-12-12'.

undelete_container(deleted_container_name: str, deleted_container_version: str, **kwargs: Any) -> ContainerClient

Parameters

Name Description
deleted_container_name
Required
str

Specifies the name of the deleted container to restore.

deleted_container_version
Required
str

Specifies the version of the deleted container to restore.

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

The undeleted ContainerClient.

Attributes

api_version

The version of the Storage API used for requests.

Returns

Type Description
str

location_mode

The location mode that the client is currently using.

By default this will be "primary". Options include "primary" and "secondary".

Returns

Type Description
str

primary_endpoint

The full primary endpoint URL.

Returns

Type Description
str

primary_hostname

The hostname of the primary endpoint.

Returns

Type Description
str

secondary_endpoint

The full secondary endpoint URL if configured.

If not available a ValueError will be raised. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.

Returns

Type Description
str

Exceptions

Type Description

secondary_hostname

The hostname of the secondary endpoint.

If not available this will be None. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.

Returns

Type Description

url

The full endpoint URL to this entity, including SAS token if used.

This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode. :returns: The full endpoint URL to this entity, including SAS token if used. :rtype: str