BlobServiceClient class

Definition

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.

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

Parameters

account_url
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 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

Creating the BlobServiceClient with account url and credential.


   from azure.storage.blob.aio import BlobServiceClient
   blob_service_client = BlobServiceClient(account_url=self.url, credential=self.shared_access_key)

Creating the BlobServiceClient with Azure Identity credentials.


   # Get a token credential for authentication
   from azure.identity.aio import ClientSecretCredential
   token_credential = ClientSecretCredential(self.active_directory_tenant_id, self.active_directory_application_id,
                                             self.active_directory_application_secret)

   # Instantiate a BlobServiceClient using a token credential
   from azure.storage.blob.aio import BlobServiceClient
   blob_service_client = BlobServiceClient(account_url=self.oauth_url, credential=token_credential)

Methods

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.

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.

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, metadata=None, public_access=None, **kwargs)

Parameters

name
str
Required

The name of the container to create.

metadata
dict(str, str)
Required

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

public_access
str or PublicAccess
Required

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

Return type

Examples

Creating a container in the blob service.


   try:
       new_container = await blob_service_client.create_container("containerfromblobserviceasync")
       properties = await new_container.get_container_properties()
   except ResourceExistsError:
       print("Container already exists.")

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, lease=None, **kwargs)

Parameters

container
str or ContainerProperties
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.

Return type

None

Examples

Deleting a container in the blob service.


   # Delete container if it exists
   try:
       await blob_service_client.delete_container("containerfromblobserviceasync")
   except ResourceNotFoundError:
       print("Container already deleted.")

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)

Examples

Getting account information for the blob service.


   account_info = await blob_service_client.get_account_information()
   print('Using Storage SKU: {}'.format(account_info['sku_name']))

get_blob_client

Get a client to interact with the specified blob.

The blob need not already exist.

get_blob_client(container, blob, snapshot=None)

Parameters

container
str or ContainerProperties
Required

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

blob
str or BlobProperties
Required

The blob with which to interact. This can either be the name of the blob, or an instance of BlobProperties.

snapshot
str or dict(str, Any)
default value: None

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(metadata=None, **kwargs).

Returns

A BlobClient.

Return type

Examples

Getting the blob client to interact with a specific blob.


   blob_client = blob_service_client.get_blob_client(container="containertestasync", blob="my_blob")
   try:
       stream = await blob_client.download_blob()
   except ResourceNotFoundError:
       print("No blob found.")

get_container_client

Get a client to interact with the specified container.

The container need not already exist.

get_container_client(container)

Parameters

container
str or ContainerProperties
Required

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

Returns

A ContainerClient.

Return type

Examples

Getting the container client to interact with a specific container.


   # Get a client to interact with a specific container - though it may not yet exist
   container_client = blob_service_client.get_container_client("containertestasync")
   try:
       blobs_list = []
       async for blob in container_client.list_blobs():
           blobs_list.append(blob)

       for blob in blobs_list:
           print("Found blob: ", blob.name)
   except ResourceNotFoundError:
       print("Container not found.")

get_service_properties

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

get_service_properties(**kwargs)

Returns

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

Return type

Dict[str, Any]

Examples

Getting service properties for the blob service.


   properties = await blob_service_client.get_service_properties()

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)

Returns

The blob service stats.

Return type

Dict[str, Any]

Examples

Getting service stats for the blob service.


   stats = await blob_service_client.get_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, key_expiry_time, **kwargs)

Parameters

key_start_time
datetime.datetime
Required

A DateTime value. Indicates when the key becomes valid.

key_expiry_time
datetime.datetime
Required

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

Returns

The user delegation key.

Return type

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=None, include_metadata=False, **kwargs)

Parameters

name_starts_with
str
Required

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

include_metadata
bool
Required

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

Returns

An iterable (auto-paging) of ContainerProperties.

Return type

Examples

Listing the containers in the blob service.


   # List all containers
   all_containers = []
   async for container in blob_service_client.list_containers(include_metadata=True):
       all_containers.append(container)

   for container in all_containers:
       print(container['name'], container['metadata'])

   # Filter results with name prefix
   test_containers = []
   async for name in blob_service_client.list_containers(name_starts_with='test-'):
       test_containers.append(name)

   for container in test_containers:
       await blob_service_client.delete_container(container)

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=None, hour_metrics=None, minute_metrics=None, cors=None, target_version=None, delete_retention_policy=None, static_website=None, **kwargs)

Parameters

analytics_logging
BlobAnalyticsLogging
Required

Groups the Azure Analytics Logging settings.

hour_metrics
Metrics
Required

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

minute_metrics
Metrics
Required

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

cors
list[CorsRule]
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
str
Required

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

delete_retention_policy
RetentionPolicy
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
StaticWebsite
Required

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

Return type

None

Examples

Setting service properties for the blob service.


   # Create service properties
   from azure.storage.blob import BlobAnalyticsLogging, Metrics, CorsRule, RetentionPolicy

   # Create logging settings
   logging = BlobAnalyticsLogging(read=True, write=True, delete=True, retention_policy=RetentionPolicy(enabled=True, days=5))

   # Create metrics for requests statistics
   hour_metrics = Metrics(enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5))
   minute_metrics = Metrics(enabled=True, include_apis=True,
                           retention_policy=RetentionPolicy(enabled=True, days=5))

   # Create CORS rules
   cors_rule = CorsRule(['www.xyz.com'], ['GET'])
   cors = [cors_rule]

   # Set the service properties
   await blob_service_client.set_service_properties(logging, hour_metrics, minute_metrics, cors)