azure.storage.fileshare.aio package

class azure.storage.fileshare.aio.ShareClient(account_url: str, share_name: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, *, token_intent: Literal['backup'] | None = None, **kwargs: Any)[source]

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

For operations relating to a specific directory or file in this share, the clients for those entities can also be retrieved using the get_directory_client() and get_file_client() functions.

Parameters:
  • account_url (str) – The URI to the storage account. In order to create a client given the full URI to the share, use the from_share_url() classmethod.

  • share_name (str) – The name of the share with which to interact.

  • snapshot (str) – An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from create_snapshot().

  • credential (AzureNamedKeyCredential or AzureSasCredential or AsyncTokenCredential or str or dict[str, str] or None) – 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.

Keyword Arguments:
  • token_intent (Literal['backup']) –

    Required when using AsyncTokenCredential for authentication and ignored for other forms of authentication. Specifies the intent for all requests when using AsyncTokenCredential authentication. Possible values are:

    backup - Specifies requests are intended for backup/admin type operations, meaning that all file/directory

    ACLs are bypassed and full permissions are granted. User must also have required RBAC permission.

  • allow_trailing_dot (bool) – If true, the trailing dot will not be trimmed from the target URI.

  • allow_source_trailing_dot (bool) – If true, the trailing dot will not be trimmed from the source URI.

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

    Added in version 12.1.0.

  • secondary_hostname (str) – The hostname of the secondary endpoint.

  • max_range_size (int) – The maximum range size used for a file upload. Defaults to 4*1024*1024.

classmethod from_connection_string(conn_str: str, share_name: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, **kwargs: Any) Self[source]

Create ShareClient from a Connection String.

Parameters:
  • conn_str (str) – A connection string to an Azure Storage account.

  • share_name (str) – The name of the share.

  • snapshot (Optional[Union[str, dict[str, Any]]]) – The optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from create_snapshot().

  • credential (AzureNamedKeyCredential or AzureSasCredential or AsyncTokenCredential or str or dict[str, str] or None) – 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 AsyncTokenCredentials 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.

Returns:

A share client.

Return type:

ShareClient

Example:

Gets the share client from connection string.
from azure.storage.fileshare.aio import ShareClient
share = ShareClient.from_connection_string(self.connection_string, "sharesamples2async")
classmethod from_share_url(share_url: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, **kwargs: Any) Self[source]
Parameters:
  • share_url (str) – The full URI to the share.

  • snapshot (Optional[Union[str, dict[str, Any]]]) – An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from create_snapshot().

  • credential (AzureNamedKeyCredential or AzureSasCredential or AsyncTokenCredential or str or dict[str, str] or None) – 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 AsyncTokenCredentials 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.

Returns:

A share client.

Return type:

ShareClient

async acquire_lease(**kwargs: Any) ShareLeaseClient[source]

Requests a new lease.

If the share does not have an active lease, the Share Service creates a lease on the share and returns a new lease.

Added in version 12.5.0.

Keyword Arguments:
  • 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 Share Service returns 400 (Invalid request) if the proposed lease ID is not in the correct format.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A ShareLeaseClient object.

Return type:

ShareLeaseClient

async close()

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

async create_directory(directory_name: str, **kwargs: Any) ShareDirectoryClient[source]

Creates a directory in the share and returns a client to interact with the directory.

Parameters:

directory_name (str) – The name of the directory.

Keyword Arguments:
Returns:

ShareDirectoryClient

Return type:

ShareDirectoryClient

async create_permission_for_share(file_permission: str, **kwargs: Any) str | None[source]

Create a permission (a security descriptor) at the share level.

This ‘permission’ can be used for the files/directories in the share. If a ‘permission’ already exists, it shall return the key of it, else creates a new permission at the share level and return its key.

Parameters:

file_permission (str) – File permission, a Portable SDDL

Keyword Arguments:
Returns:

A file permission key

Return type:

str or None

async create_share(**kwargs: Any) Dict[str, Any][source]

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

Keyword Arguments:
  • metadata (Optional[dict[str, str]]) – Name-value pairs associated with the share as metadata.

  • quota (int) – The quota to be allotted.

  • access_tier – Specifies the access tier of the share. Possible values: ‘TransactionOptimized’, ‘Hot’, ‘Cool’, ‘Premium’

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • protocols (str or ShareProtocols) – Protocols to enable on the share. Only one protocol can be enabled on the share.

  • root_squash (str or ShareRootSquash) – Root squash to set on the share. Only valid for NFS shares. Possible values include: ‘NoRootSquash’, ‘RootSquash’, ‘AllSquash’.

  • paid_bursting_enabled (bool) – This property enables paid bursting.

  • paid_bursting_bandwidth_mibps (int) – The maximum throughput the file share can support in MiB/s.

  • paid_bursting_iops (int) – The maximum IOPS the file share can support.

  • provisioned_iops (int) – The provisioned IOPS of the share, stored on the share object.

  • provisioned_bandwidth_mibps (int) – The provisioned throughput of the share, stored on the share object.

Returns:

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

Return type:

dict[str, Any]

Example:

Creates a file share.
# Create share with Access Tier set to Hot
await share.create_share(access_tier=ShareAccessTier("Hot"))
async create_snapshot(**kwargs: Any) Dict[str, Any][source]

Creates a snapshot of the share.

A snapshot is a read-only version of a share that’s taken at a point in time. It can be read, copied, or deleted, but not modified. Snapshots provide a way to back up a share as it appears at a moment in time.

A snapshot of a share has the same name as the base share from which the snapshot is taken, with a DateTime value appended to indicate the time at which the snapshot was taken.

Keyword Arguments:
Returns:

Share-updated property dict (Snapshot ID, Etag, and last modified).

Return type:

dict[str, Any]

Example:

Creates a snapshot of the file share.
await share.create_snapshot()
async delete_directory(directory_name: str, **kwargs: Any) None[source]

Marks the directory for deletion. The directory is later deleted during garbage collection.

Parameters:

directory_name (str) – The name of the directory.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Return type:

None

async delete_share(delete_snapshots: bool | Literal['include', 'include-leased'] | None = False, **kwargs: Any) None[source]

Marks the specified share for deletion. The share is later deleted during garbage collection.

Parameters:

delete_snapshots (Optional[Union[bool, Literal['include', 'include-leased']]]) – Indicates if snapshots are to be deleted. If “True” or enum “include”, snapshots will be deleted (but not include leased). To include leased snapshots, specify the “include-leased” enum.

Keyword Arguments:
  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • lease

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

    Added in version 12.5.0.

    This keyword argument was introduced in API version ‘2020-08-04’.

Example:

Deletes the share and any snapshots.
await share.delete_share(delete_snapshots=True)
get_directory_client(directory_path: str | None = None) ShareDirectoryClient[source]

Get a client to interact with the specified directory. The directory need not already exist.

Parameters:

directory_path (str) – Path to the specified directory.

Returns:

A Directory Client.

Return type:

ShareDirectoryClient

get_file_client(file_path: str) ShareFileClient[source]

Get a client to interact with the specified file. The file need not already exist.

Parameters:

file_path (str) – Path to the specified file.

Returns:

A File Client.

Return type:

ShareFileClient

async get_permission_for_share(permission_key: str, **kwargs: Any) str[source]

Get a permission (a security descriptor) for a given key.

This ‘permission’ can be used for the files/directories in the share.

Parameters:

permission_key (str) – Key of the file permission to retrieve

Keyword Arguments:
Returns:

A file permission (a portable SDDL)

Return type:

str

async get_share_access_policy(**kwargs: Any) Dict[str, Any][source]

Gets the permissions for the share. The permissions indicate whether files in a share may be accessed publicly.

Keyword Arguments:
  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • lease

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

    Added in version 12.5.0.

    This keyword argument was introduced in API version ‘2020-08-04’.

Returns:

Access policy information in a dict.

Return type:

dict[str, Any]

async get_share_properties(**kwargs: Any) ShareProperties[source]

Returns all user-defined metadata and system properties for the specified share. The data returned does not include the shares’s list of files or directories.

Keyword Arguments:
  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • lease

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

    Added in version 12.5.0.

    This keyword argument was introduced in API version ‘2020-08-04’.

Returns:

The share properties.

Return type:

ShareProperties

Example:

Gets the share properties.
properties = await share.get_share_properties()
async get_share_stats(**kwargs: Any) int[source]

Gets the approximate size of the data stored on the share in bytes.

Note that this value may not include all recently created or recently re-sized files.

Keyword Arguments:
  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • lease

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

    Added in version 12.5.0.

    This keyword argument was introduced in API version ‘2020-08-04’.

Returns:

The approximate size of the data (in bytes) stored on the share.

Return type:

int

list_directories_and_files(directory_name: str | None = None, name_starts_with: str | None = None, marker: str | None = None, **kwargs: Any) AsyncItemPaged[DirectoryProperties | FileProperties][source]

Lists the directories and files under the share.

Parameters:
  • directory_name (str) – Name of a directory.

  • name_starts_with (str) – Filters the results to return only directories whose names begin with the specified prefix.

  • marker (str) – An opaque continuation token. This value can be retrieved from the next_marker field of a previous generator object. If specified, this generator will begin returning results from this point.

Keyword Arguments:
  • include (List[str]) –

    Include this parameter to specify one or more datasets to include in the response. Possible str values are “timestamps”, “Etag”, “Attributes”, “PermissionKey”.

    Added in version 12.6.0.

    This keyword argument was introduced in API version ‘2020-10-02’.

  • include_extended_info (bool) –

    If this is set to true, file id will be returned in listed results.

    Added in version 12.6.0.

    This keyword argument was introduced in API version ‘2020-10-02’.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

An auto-paging iterable of dict-like DirectoryProperties and FileProperties

Return type:

ItemPaged[Union[DirectoryProperties, FileProperties]]

Example:

List directories and files in the share.
# Create a directory in the share
dir_client = await share.create_directory("mydir")

# Upload a file to the directory
with open(SOURCE_FILE, "rb") as source_file:
    await dir_client.upload_file(file_name="sample", data=source_file)

# List files in the directory
my_files = []
async for item in share.list_directories_and_files(directory_name="mydir"):
    my_files.append(item)
print(my_files)
async set_share_access_policy(signed_identifiers: Dict[str, AccessPolicy], **kwargs: Any) Dict[str, Any][source]

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

Parameters:

signed_identifiers (dict[str, AccessPolicy]) – A dictionary of access policies to associate with the share. The dictionary may contain up to 5 elements. An empty dictionary will clear the access policies set on the service.

Keyword Arguments:
  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • lease

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

    Added in version 12.5.0.

    This keyword argument was introduced in API version ‘2020-08-04’.

Returns:

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

Return type:

dict[str, Any]

async set_share_metadata(metadata: Dict[str, str], **kwargs: Any) Dict[str, Any][source]

Sets the metadata for the share.

Each call to this operation replaces all existing metadata attached to the share. To remove all metadata from the share, call this operation with no metadata dict.

Parameters:

metadata (dict[str, str]) – Name-value pairs associated with the share as metadata.

Keyword Arguments:
  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • lease

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

    Added in version 12.5.0.

    This keyword argument was introduced in API version ‘2020-08-04’.

Returns:

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

Return type:

dict[str, Any]

Example:

Sets the share metadata.
data = {'category': 'test'}
await share.set_share_metadata(metadata=data)
async set_share_properties(**kwargs: Any) Dict[str, Any][source]

Sets the share properties.

Added in version 12.3.0.

Keyword Arguments:
  • access_tier (str or ShareAccessTier) – Specifies the access tier of the share. Possible values: ‘TransactionOptimized’, ‘Hot’, ‘Cool’, ‘Premium’

  • quota (int) – Specifies the maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5TB.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • root_squash (str or ShareRootSquash) – Root squash to set on the share. Only valid for NFS shares. Possible values include: ‘NoRootSquash’, ‘RootSquash’, ‘AllSquash’

  • lease – Required if the share has an active lease. Value can be a ShareLeaseClient object or the lease ID as a string.

  • paid_bursting_enabled (bool) – This property enables paid bursting.

  • paid_bursting_bandwidth_mibps (int) – The maximum throughput the file share can support in MiB/s.

  • paid_bursting_iops (int) – The maximum IOPS the file share can support.

  • provisioned_iops (int) – The provisioned IOPS of the share, stored on the share object.

  • provisioned_bandwidth_mibps (int) – The provisioned throughput of the share, stored on the share object.

Returns:

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

Return type:

dict[str, Any]

Example:

Sets the share properties.
# Set the tier for the first share to Hot
await share1.set_share_properties(access_tier="Hot")
# Set the quota for the first share to 3
await share1.set_share_properties(quota=3)
# Set the tier for the second share to Cool and quota to 2
await share2.set_share_properties(access_tier=ShareAccessTier("Cool"), quota=2)

# Get the shares' properties
props1 = await share1.get_share_properties()
props2 = await share2.get_share_properties()
print(props1.access_tier)
print(props1.quota)
print(props2.access_tier)
print(props2.quota)
async set_share_quota(quota: int, **kwargs: Any) Dict[str, Any][source]

Sets the quota for the share.

Parameters:

quota (int) – Specifies the maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5TB.

Keyword Arguments:
  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • lease

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

    Added in version 12.5.0.

    This keyword argument was introduced in API version ‘2020-08-04’.

Returns:

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

Return type:

dict[str, Any]

Example:

Sets the share quota.
# Set the quota for the share to 1GB
await share.set_share_quota(quota=1)
property api_version

The version of the Storage API used for requests.

Return type:

str

property location_mode

The location mode that the client is currently using.

By default this will be “primary”. Options include “primary” and “secondary”.

Return type:

str

property primary_endpoint

The full primary endpoint URL.

Return type:

str

property primary_hostname

The hostname of the primary endpoint.

Return type:

str

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

Return type:

str

Raises:

ValueError

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

Return type:

Optional[str]

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

Return type:

str

class azure.storage.fileshare.aio.ShareDirectoryClient(account_url: str, share_name: str, directory_path: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, *, token_intent: Literal['backup'] | None = None, **kwargs: Any)[source]

A client to interact with a specific directory, although it may not yet exist.

For operations relating to a specific subdirectory or file in this share, the clients for those entities can also be retrieved using the get_subdirectory_client() and get_file_client() functions.

Parameters:
  • account_url (str) – The URI to the storage account. In order to create a client given the full URI to the directory, use the from_directory_url() classmethod.

  • share_name (str) – The name of the share for the directory.

  • directory_path (str) – The directory path for the directory with which to interact. If specified, this value will override a directory value specified in the directory URL.

  • snapshot (str) – An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from ShareClient.create_snapshot().

  • credential (AzureNamedKeyCredential or AzureSasCredential or AsyncTokenCredential or str or dict[str, str] or None) – 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 an AsyncTokenCredentials 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.

Keyword Arguments:
  • token_intent (Literal['backup']) –

    Required when using AsyncTokenCredential for authentication and ignored for other forms of authentication. Specifies the intent for all requests when using AsyncTokenCredential authentication. Possible values are:

    backup - Specifies requests are intended for backup/admin type operations, meaning that all file/directory

    ACLs are bypassed and full permissions are granted. User must also have required RBAC permission.

  • allow_trailing_dot (bool) – If true, the trailing dot will not be trimmed from the target URI.

  • allow_source_trailing_dot (bool) – If true, the trailing dot will not be trimmed from the source URI.

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

    Added in version 12.1.0.

  • secondary_hostname (str) – The hostname of the secondary endpoint.

  • max_range_size (int) – The maximum range size used for a file upload. Defaults to 4*1024*1024.

  • audience (str) – The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type AsyncTokenCredential. The value could be https://storage.azure.com/ (default) or https://<account>.file.core.windows.net.

classmethod from_connection_string(conn_str: str, share_name: str, directory_path: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, **kwargs: Any) Self[source]

Create ShareDirectoryClient from a Connection String.

Parameters:
  • conn_str (str) – A connection string to an Azure Storage account.

  • share_name (str) – The name of the share.

  • directory_path (str) – The directory path.

  • credential (Optional[Union[str, dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "AsyncTokenCredential"]]) – 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 an AsyncTokenCredentials 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.

Keyword Arguments:

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

Returns:

A directory client.

Return type:

ShareDirectoryClient

classmethod from_directory_url(directory_url: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, **kwargs: Any) Self[source]

Create a ShareDirectoryClient from a directory url.

Parameters:
  • directory_url (str) – The full URI to the directory.

  • snapshot (str) – An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from ShareClient.create_snapshot().

  • credential (AzureNamedKeyCredential or AzureSasCredential or AsyncTokenCredential or str or dict[str, str] or None) – 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 AsyncTokenCredentials 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.

Keyword Arguments:

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

Returns:

A directory client.

Return type:

ShareDirectoryClient

async close()

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

async close_all_handles(recursive: bool = False, **kwargs: Any) Dict[str, int][source]

Close any open file handles.

This operation will block until the service has closed all open handles.

Parameters:

recursive (bool) – Boolean that specifies if operation should apply to the directory specified by the client, its files, its subdirectories and their files. Default value is False.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

The number of handles closed (this may be 0 if the specified handle was not found) and the number of handles failed to close in a dict.

Return type:

dict[str, int]

async close_handle(handle: str | Handle, **kwargs: Any) Dict[str, int][source]

Close an open file handle.

Parameters:

handle (str or Handle) – A specific handle to close.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

The number of handles closed (this may be 0 if the specified handle was not found) and the number of handles failed to close in a dict.

Return type:

dict[str, int]

async create_directory(**kwargs: Any) Dict[str, Any][source]

Creates a new directory under the directory referenced by the client.

Keyword Arguments:
  • file_attributes (str or NTFSAttributes or None) – The file system attributes for files and directories. If not set, the default value would be “none” and the attributes will be set to “Archive”. Here is an example for when the var type is str: ‘Temporary|Archive’. file_attributes value is not case sensitive.

  • file_creation_time (str or datetime or None) – Creation time for the directory.

  • file_last_write_time (str or datetime or None) – Last write time for the directory.

  • file_permission (str) – If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the file-permission or file-permission-key should be specified.

  • file_permission_key (str) – Key of the permission to be set for the directory/file. Note: Only one of the file-permission or file-permission-key should be specified.

  • file_permission_format (Literal['sddl', 'binary']) – Specifies the format in which the permission is returned. If not specified, SDDL will be the default.

  • file_change_time (str or datetime) –

    Change time for the directory. If not specified, change time will be set to the current date/time.

    Added in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.

  • metadata (Optional[dict[str, str]]) – Name-value pairs associated with the directory as metadata.

  • owner (str) – NFS only. The owner of the directory.

  • group (str) – NFS only. The owning group of the directory.

  • file_mode (str) – NFS only. The file mode of the directory.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

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

Return type:

dict[str, Any]

Example:

Creates a directory.
await directory.create_directory()
async create_subdirectory(directory_name: str, **kwargs: Any) ShareDirectoryClient[source]

Creates a new subdirectory and returns a client to interact with the subdirectory.

Parameters:

directory_name (str) – The name of the subdirectory.

Keyword Arguments:
Returns:

ShareDirectoryClient

Return type:

ShareDirectoryClient

Example:

Create a subdirectory.
# Create the directory
await parent_dir.create_directory()

# Create a subdirectory
subdir = await parent_dir.create_subdirectory("subdir")
async delete_directory(**kwargs: Any) None[source]

Marks the directory for deletion. The directory is later deleted during garbage collection.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Return type:

None

Example:

Deletes a directory.
await directory.delete_directory()
async delete_file(file_name: str, **kwargs: Any) None[source]

Marks the specified file for deletion. The file is later deleted during garbage collection.

Parameters:

file_name (str) – The name of the file to delete.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Return type:

None

Example:

Delete a file in a directory.
# Delete the file in the directory
await directory.delete_file(file_name="sample")
async delete_subdirectory(directory_name: str, **kwargs: Any) None[source]

Deletes a subdirectory.

Parameters:

directory_name (str) – The name of the subdirectory.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Return type:

None

Example:

Delete a subdirectory.
await parent_dir.delete_subdirectory("subdir")
async exists(**kwargs: Any) bool[source]

Returns True if a directory exists and returns False otherwise.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

True if the directory exists, False otherwise.

Return type:

bool

async get_directory_properties(**kwargs: Any) DirectoryProperties[source]

Returns all user-defined metadata and system properties for the specified directory. The data returned does not include the directory’s list of files.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

DirectoryProperties

Return type:

DirectoryProperties

get_file_client(file_name: str, **kwargs: Any) ShareFileClient[source]

Get a client to interact with a specific file.

The file need not already exist.

Parameters:

file_name (str) – The name of the file.

Returns:

A File Client.

Return type:

ShareFileClient

get_subdirectory_client(directory_name: str, **kwargs) ShareDirectoryClient[source]

Get a client to interact with a specific subdirectory.

The subdirectory need not already exist.

Parameters:

directory_name (str) – The name of the subdirectory.

Returns:

A Directory Client.

Return type:

ShareDirectoryClient

Example:

Gets the subdirectory client.
# Get a directory client and create the directory
parent = share.get_directory_client("dir1")
await parent.create_directory()

# Get a subdirectory client and create the subdirectory "dir1/dir2"
subdirectory = parent.get_subdirectory_client("dir2")
await subdirectory.create_directory()
list_directories_and_files(name_starts_with: str | None = None, **kwargs: Any) AsyncItemPaged[DirectoryProperties | FileProperties][source]

Lists all the directories and files under the directory.

Parameters:

name_starts_with (str) – Filters the results to return only entities whose names begin with the specified prefix.

Keyword Arguments:
  • include (List[str]) –

    Include this parameter to specify one or more datasets to include in the response. Possible str values are “timestamps”, “Etag”, “Attributes”, “PermissionKey”.

    Added in version 12.6.0.

    This keyword argument was introduced in API version ‘2020-10-02’.

  • include_extended_info (bool) –

    If this is set to true, file id will be returned in listed results.

    Added in version 12.6.0.

    This keyword argument was introduced in API version ‘2020-10-02’.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

An auto-paging iterable of dict-like DirectoryProperties and FileProperties

Return type:

ItemPaged[Union[DirectoryProperties, FileProperties]]

Example:

List directories and files.
# List the directories and files under the parent directory
my_list = []
async for item in parent_dir.list_directories_and_files():
    my_list.append(item)
print(my_list)
list_handles(recursive: bool = False, **kwargs: Any) AsyncItemPaged[Handle][source]

Lists opened handles on a directory or a file under the directory.

Parameters:

recursive (bool) – Boolean that specifies if operation should apply to the directory specified by the client, its files, its subdirectories and their files. Default value is False.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

An auto-paging iterable of Handle

Return type:

AsyncItemPaged[Handle]

async rename_directory(new_name: str, **kwargs: Any) ShareDirectoryClient[source]

Rename the source directory.

Parameters:

new_name (str) – The new directory name.

Keyword Arguments:
  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • overwrite (bool) – A boolean value for if the destination file already exists, whether this request will overwrite the file or not. If true, the rename will succeed and will overwrite the destination file. If not provided or if false and the destination file does exist, the request will not overwrite the destination file. If provided and the destination file doesn’t exist, the rename will succeed.

  • ignore_read_only (bool) – A boolean value that specifies whether the ReadOnly attribute on a preexisting destination file should be respected. If true, the rename will succeed, otherwise, a previous file at the destination with the ReadOnly attribute set will cause the rename to fail.

  • file_permission (str) – If specified the permission (security descriptor) shall be set for the directory. This header can be used if Permission size is <= 8KB, else file_permission_key shall be used. If SDDL is specified as input, it must have owner, group and dacl. A value of ‘preserve’ can be passed to preserve source permissions. Note: Only one of the file_permission or file_permission_key should be specified.

  • file_permission_key (str) – Key of the permission to be set for the directory. Note: Only one of the file-permission or file-permission-key should be specified.

  • file_permission_format (Literal['sddl', 'binary']) – Specifies the format in which the permission is returned. If not specified, SDDL will be the default.

  • file_attributes (NTFSAttributes or str) – The file system attributes for the directory.

  • file_creation_time (datetime or str) – Creation time for the directory.

  • file_last_write_time (datetime or str) – Last write time for the file.

  • file_change_time (str or datetime) –

    Change time for the directory. If not specified, change time will be set to the current date/time.

    Added in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.

  • metadata (Dict[str,str]) – A name-value pair to associate with a file storage object.

  • destination_lease (ShareLeaseClient or str) – Required if the destination file has an active lease. Value can be a ShareLeaseClient object or the lease ID as a string.

Returns:

The new Directory Client.

Return type:

ShareDirectoryClient

async set_directory_metadata(metadata: Dict[str, Any], **kwargs: Any) Dict[str, Any][source]

Sets the metadata for the directory.

Each call to this operation replaces all existing metadata attached to the directory. To remove all metadata from the directory, call this operation with an empty metadata dict.

Parameters:

metadata (dict[str, str]) – Name-value pairs associated with the directory as metadata.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

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

Return type:

dict[str, Any]

async set_http_headers(file_attributes: str | NTFSAttributes | None = None, file_creation_time: str | datetime | None = None, file_last_write_time: str | datetime | None = None, file_permission: str | None = None, permission_key: str | None = None, **kwargs: Any) Dict[str, Any][source]

Sets HTTP headers on the directory.

Parameters:
  • file_attributes (str or NTFSAttributes or None) – The file system attributes for files and directories. If not set, indicates preservation of existing values. Here is an example for when the var type is str: ‘Temporary|Archive’

  • file_creation_time (str or datetime or None) – Creation time for the file

  • file_last_write_time (str or datetime or None) – Last write time for the file

  • file_permission (str) – If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.

  • permission_key (str) – Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.

Keyword Arguments:
  • file_permission_format (Literal['sddl', 'binary']) – Specifies the format in which the permission is returned. If not specified, SDDL will be the default.

  • file_change_time (str or datetime) –

    Change time for the directory. If not specified, change time will be set to the current date/time.

    Added in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.

  • owner (str) – NFS only. The owner of the directory.

  • group (str) – NFS only. The owning group of the directory.

  • file_mode (str) – NFS only. The file mode of the directory.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

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

Return type:

dict[str, Any]

async upload_file(file_name: str, data: bytes | str | Iterable | AsyncIterable | IO, length: int | None = None, **kwargs: Any) ShareFileClient[source]

Creates a new file in the directory and returns a ShareFileClient to interact with the file.

Parameters:
  • file_name (str) – The name of the file.

  • data (Union[bytes, str, Iterable[AnyStr], AsyncIterable[AnyStr], IO[AnyStr]]) – Content of the file.

  • length (int) – Length of the file in bytes. Specify its maximum size, up to 1 TiB.

Keyword Arguments:
  • metadata (Optional[dict[str, str]]) – Name-value pairs associated with the file as metadata.

  • content_settings (ContentSettings) – ContentSettings object used to set file properties. Used to set content type, encoding, language, disposition, md5, and cache control.

  • validate_content (bool) – If true, calculates an MD5 hash for each range of the file. The storage service checks the hash of the content that has arrived with the hash that was sent. This is primarily valuable for detecting bitflips on the wire if using http instead of https as https (the default) will already validate. Note that this MD5 hash is not stored with the file.

  • max_concurrency (int) – Maximum number of parallel connections to use.

  • progress_hook (Callable[[int, Optional[int]], Awaitable[None]]) – An async callback to track the progress of a long running upload. The signature is function(current: int, total: Optional[int]) where current is the number of bytes transferred so far, and total is the size of the blob or None if the size is unknown.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • encoding (str) – Defaults to UTF-8.

Returns:

ShareFileClient

Return type:

ShareFileClient

Example:

Upload a file to a directory.
# Upload a file to the directory
with open(SOURCE_FILE, "rb") as source:
    await directory.upload_file(file_name="sample", data=source)
property api_version

The version of the Storage API used for requests.

Return type:

str

property location_mode

The location mode that the client is currently using.

By default this will be “primary”. Options include “primary” and “secondary”.

Return type:

str

property primary_endpoint

The full primary endpoint URL.

Return type:

str

property primary_hostname

The hostname of the primary endpoint.

Return type:

str

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

Return type:

str

Raises:

ValueError

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

Return type:

Optional[str]

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

Return type:

str

class azure.storage.fileshare.aio.ShareFileClient(account_url: str, share_name: str, file_path: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, *, token_intent: Literal['backup'] | None = None, **kwargs: Any)[source]

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

Parameters:
  • account_url (str) – The URI to the storage account. In order to create a client given the full URI to the file, use the from_file_url() classmethod.

  • share_name (str) – The name of the share for the file.

  • file_path (str) – The file path to the file with which to interact. If specified, this value will override a file value specified in the file URL.

  • snapshot (str) – An optional file snapshot on which to operate. This can be the snapshot ID string or the response returned from ShareClient.create_snapshot().

  • credential (AzureNamedKeyCredential or AzureSasCredential or AsyncTokenCredential or str or dict[str, str] or None) – 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 AsyncTokenCredentials 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.

Keyword Arguments:
  • token_intent (Literal['backup']) –

    Required when using AsyncTokenCredential for authentication and ignored for other forms of authentication. Specifies the intent for all requests when using AsyncTokenCredential authentication. Possible values are:

    backup - Specifies requests are intended for backup/admin type operations, meaning that all file/directory

    ACLs are bypassed and full permissions are granted. User must also have required RBAC permission.

  • allow_trailing_dot (bool) – If true, the trailing dot will not be trimmed from the target URI.

  • allow_source_trailing_dot (bool) – If true, the trailing dot will not be trimmed from the source URI.

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

    Added in version 12.1.0.

  • secondary_hostname (str) – The hostname of the secondary endpoint.

  • max_range_size (int) – The maximum range size used for a file upload. Defaults to 4*1024*1024.

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

classmethod from_connection_string(conn_str: str, share_name: str, file_path: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, **kwargs: Any) Self[source]

Create ShareFileClient from a Connection String.

Parameters:
  • conn_str (str) – A connection string to an Azure Storage account.

  • share_name (str) – The name of the share.

  • file_path (str) – The file path.

  • snapshot (str) – An optional file snapshot on which to operate. This can be the snapshot ID string or the response returned from ShareClient.create_snapshot().

  • credential (AzureNamedKeyCredential or AzureSasCredential or AsyncTokenCredential or str or dict[str, str] or None) – 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 AsyncTokenCredentials 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.

Keyword Arguments:

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

Returns:

A File client.

Return type:

ShareFileClient

Example:

Creates the file client with connection string.
    from azure.storage.fileshare.aio import ShareFileClient
    file = ShareFileClient.from_connection_string(
        self.connection_string,
        share_name='helloworld2async',
        file_path="myfile")
classmethod from_file_url(file_url: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, **kwargs: Any) Self[source]

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

Parameters:
  • file_url (str) – The full URI to the file.

  • snapshot (str) – An optional file snapshot on which to operate. This can be the snapshot ID string or the response returned from ShareClient.create_snapshot().

  • credential (AzureNamedKeyCredential or AzureSasCredential or AsyncTokenCredential or str or dict[str, str] or None) – 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 AsyncTokenCredentials 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.

Keyword Arguments:

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

Returns:

A File client.

Return type:

ShareFileClient

async abort_copy(copy_id: str | FileProperties, **kwargs: Any) None[source]

Abort an ongoing copy operation.

This will leave a destination file with zero length and full metadata. This will raise an error if the copy operation has already ended.

Parameters:

copy_id (str or FileProperties) – The copy operation to abort. This can be either an ID, or an instance of FileProperties.

Keyword Arguments:
Return type:

None

async acquire_lease(lease_id: str | None = None, **kwargs: Any) ShareLeaseClient[source]

Requests a new lease.

If the file does not have an active lease, the File Service creates a lease on the blob and returns a new lease.

Parameters:

lease_id (str) – Proposed lease ID, in a GUID string format. The File Service returns 400 (Invalid request) if the proposed lease ID is not in the correct format.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A ShareLeaseClient object.

Return type:

ShareLeaseClient

async clear_range(offset: int, length: int, **kwargs: Any) Dict[str, Any][source]

Clears the specified range and releases the space used in storage for that range.

Parameters:
  • offset (int) – Start of byte range to use for clearing a section of the file. The range can be up to 4 MB in size.

  • length (int) – Number of bytes to use for clearing a section of the file. The range can be up to 4 MB in size.

Keyword Arguments:
Returns:

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

Return type:

Dict[str, Any]

async close()

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

async close_all_handles(**kwargs: Any) Dict[str, int][source]

Close any open file handles.

This operation will block until the service has closed all open handles.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

The number of handles closed (this may be 0 if the specified handle was not found) and the number of handles failed to close in a dict.

Return type:

dict[str, int]

async close_handle(handle: str | Handle, **kwargs: Any) Dict[str, int][source]

Close an open file handle.

Parameters:

handle (str or Handle) – A specific handle to close.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

The number of handles closed (this may be 0 if the specified handle was not found) and the number of handles failed to close in a dict.

Return type:

dict[str, int]

async create_file(size: int, file_attributes: str | NTFSAttributes | None = None, file_creation_time: str | datetime | None = None, file_last_write_time: str | datetime | None = None, file_permission: str | None = None, permission_key: str | None = None, **kwargs: Any) Dict[str, Any][source]

Creates a new file.

Note that it only initializes the file with no content.

Parameters:
  • size (int) – Specifies the maximum size for the file, up to 1 TB.

  • file_attributes (str or NTFSAttributes or None) – The file system attributes for files and directories. If not set, the default value would be “None” and the attributes will be set to “Archive”. Here is an example for when the var type is str: ‘Temporary|Archive’. file_attributes value is not case sensitive.

  • file_creation_time (str or datetime or None) – Creation time for the file

  • file_last_write_time (str or datetime or None) – Last write time for the file

  • file_permission (str) – If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.

  • permission_key (str) – Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.

Keyword Arguments:
  • file_permission_format (Literal['sddl', 'binary']) – Specifies the format in which the permission is returned. If not specified, SDDL will be the default.

  • file_change_time (str or datetime) –

    Change time for the file. If not specified, change time will be set to the current date/time.

    Added in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.

  • content_settings (ContentSettings) – ContentSettings object used to set file properties. Used to set content type, encoding, language, disposition, md5, and cache control.

  • metadata (Optional[dict[str, str]]) – Name-value pairs associated with the file as metadata.

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

  • owner (str) – NFS only. The owner of the file.

  • group (str) – NFS only. The owning group of the file.

  • file_mode (str) – NFS only. The file mode of the file.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

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

Return type:

dict[str, Any]

Example:

Create a file.
# Create and allocate bytes for the file (no content added yet)
await my_allocated_file.create_file(size=100)

NFS only. Creates a hard link to the file specified by path.

Parameters:

target (str) – Specifies the path of the target file to which the link will be created, up to 2 KiB in length. It should be the full path of the target starting from the root. The target file must be in the same share and the same storage account.

Keyword Arguments:
Returns:

File-updated property dict (ETag and last modified).

Return type:

dict[str, Any]

NFS only. Creates a symbolic link to the specified file.

Parameters:

target (str) – Specifies the file path the symbolic link will point to. The file path can be either relative or absolute.

Keyword Arguments:
Returns:

File-updated property dict (ETag and last modified).

Return type:

dict[str, Any]

async delete_file(**kwargs: Any) None[source]

Marks the specified file for deletion. The file is later deleted during garbage collection.

Keyword Arguments:
Return type:

None

Example:

Delete a file.
await my_file.delete_file()
async download_file(offset: int | None = None, length: int | None = None, **kwargs: Any) StorageStreamDownloader[source]

Downloads a file to the StorageStreamDownloader. The readall() method must be used to read all the content or readinto() must be used to download the file into a stream. Using chunks() returns an async iterator which allows the user to iterate over the content in chunks.

Parameters:
  • offset (int) – Start of byte range to use for downloading a section of the file. 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.

Keyword Arguments:
  • max_concurrency (int) – Maximum number of parallel connections to use when transferring the file in chunks. This option does not affect the underlying connection pool, and may require a separate configuration of the connection pool.

  • validate_content (bool) – If true, calculates an MD5 hash for each chunk of the file. The storage service checks the hash of the content that has arrived with the hash that was sent. This is primarily valuable for detecting bitflips on the wire if using http instead of https as https (the default) will already validate. Note that this MD5 hash is not stored with the file. Also note that if enabled, the memory-efficient upload algorithm will not be used, because computing the MD5 hash requires buffering entire blocks, and doing so defeats the purpose of the memory-efficient algorithm.

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

  • progress_hook (Callable[[int, int], Awaitable[None]]) – An async callback to track the progress of a long running download. The signature is function(current: int, total: int) where current is the number of bytes transferred so far, and total is the size of the blob or None if the size is unknown.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A streaming object (StorageStreamDownloader)

Return type:

StorageStreamDownloader

Example:

Download a file.
with open(DEST_FILE, "wb") as data:
    stream = await my_file.download_file()
    data.write(await stream.readall())
async exists(**kwargs: Any) bool[source]

Returns True if the file exists and returns False otherwise.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

True if the file exists, False otherwise.

Return type:

bool

async get_file_properties(**kwargs: Any) FileProperties[source]

Returns all user-defined metadata, standard HTTP properties, and system properties for the file.

Keyword Arguments:
Returns:

FileProperties

Return type:

FileProperties

async get_ranges(offset: int | None = None, length: int | None = None, **kwargs: Any) List[Dict[str, int]][source]

Returns the list of valid page ranges for a file or snapshot of a file.

Parameters:
  • offset (int) – Specifies the start offset of bytes over which to get ranges.

  • length (int) – Number of bytes to use over which to get ranges.

Keyword Arguments:
Returns:

A list of valid ranges.

Return type:

List[dict[str, int]]

async get_ranges_diff(previous_sharesnapshot: str | Dict[str, Any], offset: int | None = None, length: int | None = None, *, include_renames: bool | None = None, **kwargs: Any) Tuple[List[Dict[str, int]], List[Dict[str, int]]][source]

Returns the list of valid page ranges for a file or snapshot of a file.

Added in version 12.6.0.

Parameters:
  • offset (int) – Specifies the start offset of bytes over which to get ranges.

  • length (int) – Number of bytes to use over which to get ranges.

  • previous_sharesnapshot (str) – The snapshot diff parameter that contains an opaque DateTime value that specifies a previous file snapshot to be compared against a more recent snapshot or the current file.

Keyword Arguments:
  • include_renames (Optional[bool]) – Only valid if previous_sharesnapshot parameter is provided. Specifies whether the changed ranges for a file that has been renamed or moved between the target snapshot (or live file) and the previous snapshot should be listed. If set to True, the valid changed ranges for the file will be returned. If set to False, the operation will result in a 409 (Conflict) response.

  • lease (ShareLeaseClient or str) – Required if the file has an active lease. Value can be a ShareLeaseClient object or the lease ID as a string.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A tuple of two lists of file ranges as dictionaries with ‘start’ and ‘end’ keys. The first element are filled file ranges, the 2nd element is cleared file ranges.

Return type:

tuple[list[dict[str, int]], list[dict[str, int]]]

NFS only. Gets the symbolic link for the file client.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timeouts see here.

Returns:

File-updated property dict (ETag and last modified).

Return type:

dict[str, Any]

list_handles(**kwargs: Any) AsyncItemPaged[Handle][source]

Lists handles for file.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

An auto-paging iterable of Handle

Return type:

AsyncItemPaged[Handle]

async rename_file(new_name: str, **kwargs: Any) ShareFileClient[source]

Rename the source file.

Parameters:

new_name (str) – The new file name.

Keyword Arguments:
  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • overwrite (bool) – A boolean value for if the destination file already exists, whether this request will overwrite the file or not. If true, the rename will succeed and will overwrite the destination file. If not provided or if false and the destination file does exist, the request will not overwrite the destination file. If provided and the destination file doesn’t exist, the rename will succeed.

  • ignore_read_only (bool) – A boolean value that specifies whether the ReadOnly attribute on a preexisting destination file should be respected. If true, the rename will succeed, otherwise, a previous file at the destination with the ReadOnly attribute set will cause the rename to fail.

  • file_permission (str) – If specified the permission (security descriptor) shall be set for the file. This header can be used if Permission size is <= 8KB, else file_permission_key shall be used. If SDDL is specified as input, it must have owner, group and dacl. A value of ‘preserve’ can be passed to preserve source permissions. Note: Only one of the file_permission or file_permission_key should be specified.

  • file_permission_key (str) – Key of the permission to be set for the file. Note: Only one of the file-permission or file-permission-key should be specified.

  • file_permission_format (Literal['sddl', 'binary']) – Specifies the format in which the permission is returned. If not specified, SDDL will be the default.

  • file_attributes (NTFSAttributes or str) – The file system attributes for the file.

  • file_creation_time (datetime or str) – Creation time for the file.

  • file_last_write_time (datetime or str) – Last write time for the file.

  • file_change_time (str or datetime) –

    Change time for the file. If not specified, change time will be set to the current date/time.

    Added in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.

  • content_type (str) –

    The Content Type of the new file.

    Added in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.

  • metadata (Dict[str,str]) – A name-value pair to associate with a file storage object.

  • source_lease (ShareLeaseClient or str) – Required if the source file has an active lease. Value can be a ShareLeaseClient object or the lease ID as a string.

  • destination_lease (ShareLeaseClient or str) – Required if the destination file has an active lease. Value can be a ShareLeaseClient object or the lease ID as a string.

Returns:

The new File Client.

Return type:

ShareFileClient

async resize_file(size: int, **kwargs: Any) Dict[str, Any][source]

Resizes a file to the specified size.

Parameters:

size (int) – Size to resize file to (in bytes)

Keyword Arguments:
Returns:

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

Return type:

Dict[str, Any]

async set_file_metadata(metadata: Dict[str, Any] | None = None, **kwargs: Any) Dict[str, Any][source]

Sets user-defined metadata for the specified file as one or more name-value pairs.

Each call to this operation replaces all existing metadata attached to the file. To remove all metadata from the file, call this operation with no metadata dict.

Parameters:

metadata (dict[str, str]) – Name-value pairs associated with the file as metadata.

Keyword Arguments:
Returns:

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

Return type:

dict[str, Any]

async set_http_headers(content_settings: ContentSettings, file_attributes: str | NTFSAttributes | None = None, file_creation_time: str | datetime | None = None, file_last_write_time: str | datetime | None = None, file_permission: str | None = None, permission_key: str | None = None, **kwargs: Any) Dict[str, Any][source]

Sets HTTP headers on the file.

Parameters:
  • content_settings (ContentSettings) – ContentSettings object used to set file properties. Used to set content type, encoding, language, disposition, md5, and cache control.

  • file_attributes (str or NTFSAttributes or None) – The file system attributes for files and directories. If not set, indicates preservation of existing values. Here is an example for when the var type is str: ‘Temporary|Archive’

  • file_creation_time (str or datetime or None) – Creation time for the file

  • file_last_write_time (str or datetime or None) – Last write time for the file

  • file_permission (str) – If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.

  • permission_key (str) – Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.

Keyword Arguments:
  • file_permission_format (Literal['sddl', 'binary']) – Specifies the format in which the permission is returned. If not specified, SDDL will be the default.

  • file_change_time (str or datetime) –

    Change time for the file. If not specified, change time will be set to the current date/time.

    Added in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

  • owner (str) – NFS only. The owner of the file.

  • group (str) – NFS only. The owning group of the file.

  • file_mode (str) – NFS only. The file mode of the file.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

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

Return type:

dict[str, Any]

async start_copy_from_url(source_url: str, **kwargs: Any) Dict[str, Any][source]

Initiates the copying of data from a source URL into the file referenced by the client.

The status of this copy operation can be found using the get_properties method.

Parameters:

source_url (str) – Specifies the URL of the source file.

Keyword Arguments:
  • file_permission (str) –

    If specified the permission (security descriptor) shall be set for the directory/file. This value can be set to “source” to copy the security descriptor from the source file. Otherwise if set, this value will be used to override the source value. If not set, permission value is inherited from the parent directory of the target file. This setting can be used if Permission size is <= 8KB, otherwise permission_key shall be used. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the file_permission or permission_key should be specified.

    Added in version 12.1.0: This parameter was introduced in API version ‘2019-07-07’.

  • permission_key (str) –

    Key of the permission to be set for the directory/file. This value can be set to “source” to copy the security descriptor from the source file. Otherwise if set, this value will be used to override the source value. If not set, permission value is inherited from the parent directory of the target file. Note: Only one of the file_permission or permission_key should be specified.

    Added in version 12.1.0: This parameter was introduced in API version ‘2019-07-07’.

  • file_permission_format (Literal['sddl', 'binary']) – Specifies the format in which the permission is returned. If not specified, SDDL will be the default.

  • file_attributes (str or NTFSAttributes) –

    This value can be set to “source” to copy file attributes from the source file to the target file, or to clear all attributes, it can be set to “None”. Otherwise it can be set to a list of attributes to set on the target file. If this is not set, the default value is “Archive”.

    Added in version 12.1.0: This parameter was introduced in API version ‘2019-07-07’.

  • file_creation_time (str or datetime) –

    This value can be set to “source” to copy the creation time from the source file to the target file, or a datetime to set as creation time on the target file. This could also be a string in ISO 8601 format. If this is not set, creation time will be set to the date time value of the creation (or when it was overwritten) of the target file by copy engine.

    Added in version 12.1.0: This parameter was introduced in API version ‘2019-07-07’.

  • file_last_write_time (str or datetime) –

    This value can be set to “source” to copy the last write time from the source file to the target file, or a datetime to set as the last write time on the target file. This could also be a string in ISO 8601 format. If this is not set, value will be the last write time to the file by the copy engine.

    Added in version 12.1.0: This parameter was introduced in API version ‘2019-07-07’.

  • file_change_time (str or datetime) –

    Change time for the file. If not specified, change time will be set to the current date/time.

    Added in version 12.9.0: This parameter was introduced in API version ‘2021-06-08’.

  • ignore_read_only (bool) –

    Specifies the option to overwrite the target file if it already exists and has read-only attribute set.

    Added in version 12.1.0: This parameter was introduced in API version ‘2019-07-07’.

  • set_archive_attribute (bool) –

    Specifies the option to set the archive attribute on the target file. True means the archive attribute will be set on the target file despite attribute overrides or the source file state.

    Added in version 12.1.0: This parameter was introduced in API version ‘2019-07-07’.

  • metadata (Optional[dict[str, str]]) – Name-value pairs associated with the file as metadata.

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

  • owner (str) – NFS only. The owner of the file.

  • group (str) – NFS only. The owning group of the file.

  • file_mode (str) – NFS only. The file mode of the file.

  • file_mode_copy_mode (Literal['source', 'override']) –

    NFS only. Applicable only when the copy source is a File. Determines the copy behavior of the mode bits of the file. Possible values are:

    source - The mode on the destination file is copied from the source file. override - The mode on the destination file is determined via the file_mode keyword.

  • owner_copy_mode (Literal['source', 'override']) –

    NFS only. Applicable only when the copy source is a File. Determines the copy behavior of the owner and group of the file. Possible values are:

    source - The owner and group on the destination file is copied from the source file. override - The owner and group on the destination file is determined via the owner and group keywords.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

Response after data copying operation has been initiated.

Return type:

dict[str, Any]

Example:

Copy a file from a URL
await destination_file.start_copy_from_url(source_url=source_url)
async upload_file(data: bytes | str | Iterable | AsyncIterable | IO, length: int | None = None, file_attributes: str | NTFSAttributes | None = None, file_creation_time: str | datetime | None = None, file_last_write_time: str | datetime | None = None, file_permission: str | None = None, permission_key: str | None = None, **kwargs) Dict[str, Any][source]

Uploads a new file.

Parameters:
  • data (Union[bytes, str, Iterable[AnyStr], AsyncIterable[AnyStr], IO[AnyStr]]) – Content of the file.

  • length (int) – Length of the file in bytes. Specify its maximum size, up to 1 TiB.

  • file_attributes (str or NTFSAttributes or None) – The file system attributes for files and directories. If not set, the default value would be “None” and the attributes will be set to “Archive”. Here is an example for when the var type is str: ‘Temporary|Archive’. file_attributes value is not case sensitive.

  • file_creation_time (str or datetime or None) – Creation time for the file

  • file_last_write_time (str or datetime or None) – Last write time for the file

  • file_permission (str) – If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.

  • permission_key (str) – Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.

Keyword Arguments:
  • file_change_time (str or datetime) –

    Change time for the file. If not specified, change time will be set to the current date/time.

    Added in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.

  • metadata (Optional[dict[str, str]]) – Name-value pairs associated with the file as metadata.

  • content_settings (ContentSettings) – ContentSettings object used to set file properties. Used to set content type, encoding, language, disposition, md5, and cache control.

  • validate_content (bool) – If true, calculates an MD5 hash for each range of the file. The storage service checks the hash of the content that has arrived with the hash that was sent. This is primarily valuable for detecting bitflips on the wire if using http instead of https as https (the default) will already validate. Note that this MD5 hash is not stored with the file.

  • max_concurrency (int) – Maximum number of parallel connections to use when transferring the file in chunks. This option does not affect the underlying connection pool, and may require a separate configuration of the connection pool.

  • encoding (str) – Defaults to UTF-8.

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

  • progress_hook (Callable[[int, Optional[int]], Awaitable[None]]) – An async callback to track the progress of a long running upload. The signature is function(current: int, total: Optional[int]) where current is the number of bytes transferred so far, and total is the size of the blob or None if the size is unknown.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

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

Return type:

dict[str, Any]

Example:

Upload a file.
with open(SOURCE_FILE, "rb") as source:
    await my_file.upload_file(source)
async upload_range(data: bytes, offset: int, length: int, **kwargs: Any) Dict[str, Any][source]

Upload a range of bytes to a file.

Parameters:
  • data (bytes) – The data to upload.

  • offset (int) – Start of byte range to use for uploading a section of the file. The range can be up to 4 MB in size.

  • length (int) – Number of bytes to use for uploading a section of the file. The range can be up to 4 MB in size.

Keyword Arguments:
  • validate_content (bool) – If true, calculates an MD5 hash of the page content. The storage service checks the hash of the content that has arrived with the hash that was sent. This is primarily valuable for detecting bitflips on the wire if using http instead of https as https (the default) will already validate. Note that this MD5 hash is not stored with the file.

  • file_last_write_mode (Literal["preserve", "now"]) –

    If the file last write time should be preserved or overwritten. Possible values are “preserve” or “now”. If not specified, file last write time will be changed to the current date/time.

    Added in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • encoding (str) – Defaults to UTF-8.

Returns:

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

Return type:

Dict[str, Any]

async upload_range_from_url(source_url: str, offset: int, length: int, source_offset: int, **kwargs: Any) Dict[str, Any][source]

Writes the bytes from one Azure File endpoint into the specified range of another Azure File endpoint.

Parameters:
  • offset (int) – Start of byte range to use for updating a section of the file. The range can be up to 4 MB in size.

  • length (int) – Number of bytes to use for updating a section of the file. The range can be up to 4 MB in size.

  • source_url (str) – A URL of up to 2 KB in length that specifies an Azure file or blob. The value should be URL-encoded as it would appear in a request URI. If the source is in another account, the source must either be public or must be authenticated via a shared access signature. If the source is public, no authentication is required. Examples: https://myaccount.file.core.windows.net/myshare/mydir/myfile https://otheraccount.file.core.windows.net/myshare/mydir/myfile?sastoken

  • source_offset (int) – This indicates the start of the range of bytes(inclusive) that has to be taken from the copy source. The service will read the same number of bytes as the destination range (length-offset).

Keyword Arguments:
  • source_if_modified_since (datetime) – 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 conditional header to copy the blob only if the source blob has been modified since the specified date/time.

  • source_if_unmodified_since (datetime) – 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 conditional header to copy the blob only if the source blob has not been modified since the specified date/time.

  • source_etag (str) – The source 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.

  • source_match_condition (MatchConditions) – The source match condition to use upon the etag.

  • file_last_write_mode (Literal["preserve", "now"]) –

    If the file last write time should be preserved or overwritten. Possible values are “preserve” or “now”. If not specified, file last write time will be changed to the current date/time.

    Added in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • source_authorization (str) – Authenticate as a service principal using a client secret to access a source blob. Ensure “bearer “ is the prefix of the source_authorization string.

Returns:

Result after writing to the specified range of the destination Azure File endpoint.

Return type:

dict[str, Any]

property api_version

The version of the Storage API used for requests.

Return type:

str

property location_mode

The location mode that the client is currently using.

By default this will be “primary”. Options include “primary” and “secondary”.

Return type:

str

property primary_endpoint

The full primary endpoint URL.

Return type:

str

property primary_hostname

The hostname of the primary endpoint.

Return type:

str

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

Return type:

str

Raises:

ValueError

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

Return type:

Optional[str]

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

Return type:

str

class azure.storage.fileshare.aio.ShareLeaseClient(client: ShareFileClient | ShareClient, lease_id: str | None = None)[source]

Creates a new ShareLeaseClient.

This client provides lease operations on a ShareClient or ShareFileClient.

Variables:
  • id (str) – The ID of the lease currently being maintained. This will be None if no lease has yet been acquired.

  • etag (str) – The ETag of the lease currently being maintained. This will be None if no lease has yet been acquired or modified.

  • last_modified (datetime) – The last modified timestamp of the lease currently being maintained. This will be None if no lease has yet been acquired or modified.

Parameters:
  • client (ShareFileClient or ShareClient) – The client of the file or share to lease.

  • lease_id (str) – A string representing the lease ID of an existing lease. This value does not need to be specified in order to acquire a new lease, or break one.

async acquire(**kwargs: Any) None[source]

Requests a new lease. This operation establishes and manages a lock on a file or share for write and delete operations. If the file or share does not have an active lease, the File or Share service creates a lease on the file or share. If the file has an active lease, you can only request a new lease using the active lease ID.

If the file or share does not have an active lease, the File or Share service creates a lease on the file and returns a new lease ID.

Keyword Arguments:
  • lease_duration (int) – Specifies the duration of the lease, in seconds, or negative one (-1) for a lease that never expires. File leases never expire. A non-infinite share lease can be between 15 and 60 seconds. A share lease duration cannot be changed using renew or change. Default is -1 (infinite share lease).

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Return type:

None

async break_lease(**kwargs: Any) int[source]

Force breaks the lease if the file or share has an active lease. Any authorized request can break the lease; the request is not required to specify a matching lease ID. An infinite lease breaks immediately.

Once a lease is broken, it cannot be changed. Any authorized request can break the lease; the request is not required to specify a matching lease ID. When a lease is successfully broken, the response indicates the interval in seconds until a new lease can be acquired.

Keyword Arguments:
  • lease_break_period (int) –

    This is the proposed duration of seconds that the share lease should continue before it is broken, between 0 and 60 seconds. This break period is only used if it is shorter than the time remaining on the share lease. If longer, the time remaining on the share lease is used. A new share lease will not be available before the break period has expired, but the share lease may be held for longer than the break period. If this header does not appear with a break operation, a fixed-duration share lease breaks after the remaining share lease period elapses, and an infinite share lease breaks immediately.

    Added in version 12.5.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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

Approximate time remaining in the lease period, in seconds.

Return type:

int

async change(proposed_lease_id: str, **kwargs: Any) None[source]

Changes the lease ID of an active lease. A change must include the current lease ID in x-ms-lease-id and a new lease ID in x-ms-proposed-lease-id.

Parameters:

proposed_lease_id (str) – Proposed lease ID, in a GUID string format. The File or Share service raises an error (Invalid request) if the proposed lease ID is not in the correct format.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

None

async release(**kwargs: Any) None[source]

Releases the lease. The lease may be released if the lease ID specified on the request matches that associated with the share or file. Releasing the lease allows another client to immediately acquire the lease for the share or file as soon as the release is complete.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

None

async renew(**kwargs: Any) None[source]

Renews the share lease.

The share lease can be renewed if the lease ID specified in the lease client matches that associated with the share. Note that the lease may be renewed even if it has expired as long as the share has not been leased again since the expiration of that lease. When you renew a lease, the lease duration clock resets.

Added in version 12.6.0.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

None

class azure.storage.fileshare.aio.ShareServiceClient(account_url: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, *, token_intent: Literal['backup'] | None = None, **kwargs: Any)[source]

A client to interact with the File Share Service at the account level.

This client provides operations to retrieve and configure the account properties as well as list, create and delete shares within the account. For operations relating to a specific share, a client for that entity can also be retrieved using the get_share_client() function.

Parameters:
  • account_url (str) – The URL to the file share storage account. Any other entities included in the URL path (e.g. share or file) will be discarded. This URL can be optionally authenticated with a SAS token.

  • credential (AzureNamedKeyCredential or AzureSasCredential or AsyncTokenCredential or str or dict[str, str] or None) – 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 AsyncTokenCredentials 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.

Keyword Arguments:
  • token_intent (Literal['backup']) –

    Required when using AsyncTokenCredential for authentication and ignored for other forms of authentication. Specifies the intent for all requests when using AsyncTokenCredential authentication. Possible values are:

    backup - Specifies requests are intended for backup/admin type operations, meaning that all file/directory

    ACLs are bypassed and full permissions are granted. User must also have required RBAC permission.

  • allow_trailing_dot (bool) – If true, the trailing dot will not be trimmed from the target URI.

  • allow_source_trailing_dot (bool) – If true, the trailing dot will not be trimmed from the source URI.

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

    Added in version 12.1.0.

  • secondary_hostname (str) – The hostname of the secondary endpoint.

  • max_range_size (int) – The maximum range size used for a file upload. Defaults to 4*1024*1024.

Example:

Create the share service client with url and credential.
from azure.storage.fileshare.aio import ShareServiceClient
share_service_client = ShareServiceClient(
    account_url=self.account_url,
    credential=self.access_key
)
classmethod from_connection_string(conn_str: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, **kwargs: Any) Self[source]

Create ShareServiceClient from a Connection String.

Parameters:
  • conn_str (str) – A connection string to an Azure Storage account.

  • credential (AzureNamedKeyCredential or AzureSasCredential or AsyncTokenCredential or str or dict[str, str] or None) – 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 AsyncTokenCredentials 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.

Returns:

A File Share service client.

Return type:

ShareServiceClient

Example:

Create the share service client with connection string.
from azure.storage.fileshare.aio import ShareServiceClient
file_service = ShareServiceClient.from_connection_string(self.connection_string)
async close()

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

async create_share(share_name: str, **kwargs: Any) ShareClient[source]

Creates a new share under the specified account. If the share with the same name already exists, the operation fails. Returns a client with which to interact with the newly created share.

Parameters:

share_name (str) – The name of the share to create.

Keyword Arguments:
  • metadata (dict[str, str]) – A dict with name_value pairs to associate with the share as metadata. Example:{‘Category’:’test’}

  • quota (int) – Quota in bytes.

  • 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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

  • provisioned_iops (int) – The provisioned IOPS of the share, stored on the share object.

  • provisioned_bandwidth_mibps (int) – The provisioned throughput of the share, stored on the share object.

Returns:

A ShareClient for the newly created Share.

Return type:

ShareClient

Example:

Create a share in the file share service.
await file_service.create_share(share_name="fileshare1async")
async delete_share(share_name: ShareProperties | str, delete_snapshots: bool | None = False, **kwargs: Any) None[source]

Marks the specified share for deletion. The share is later deleted during garbage collection.

Parameters:
  • share_name (str or ShareProperties) – The share to delete. This can either be the name of the share, or an instance of ShareProperties.

  • delete_snapshots (bool) – Indicates if snapshots are to be deleted.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Return type:

None

Example:

Delete a share in the file share service.
await file_service.delete_share(share_name="fileshare1async")
async get_service_properties(**kwargs: Any) Dict[str, Any][source]

Gets the properties of a storage account’s File Share service, including Azure Storage Analytics.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A dictionary containing file service properties such as analytics logging, hour/minute metrics, cors rules, etc.

Return type:

Dict[str, Any]

Example:

Get file share service properties.
properties = await file_service.get_service_properties()
get_share_client(share: ShareProperties | str, snapshot: str | Dict[str, Any] | None = None) ShareClient[source]

Get a client to interact with the specified share. The share need not already exist.

Parameters:
  • share (str or ShareProperties) – The share. This can either be the name of the share, or an instance of ShareProperties.

  • snapshot (str) – An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from create_snapshot().

Returns:

A ShareClient.

Return type:

ShareClient

Example:

Gets the share client.
from azure.storage.fileshare.aio import ShareServiceClient
file_service = ShareServiceClient.from_connection_string(self.connection_string)

# Get a share client to interact with a specific share
share = file_service.get_share_client("fileshare2")
list_shares(name_starts_with: str | None = None, include_metadata: bool | None = False, include_snapshots: bool | None = False, **kwargs: Any) AsyncItemPaged[ShareProperties][source]

Returns auto-paging iterable of dict-like ShareProperties under the specified account. The generator will lazily follow the continuation tokens returned by the service and stop when all shares have been returned.

Parameters:
  • name_starts_with (str) – Filters the results to return only shares whose names begin with the specified name_starts_with.

  • include_metadata (bool) – Specifies that share metadata be returned in the response.

  • include_snapshots (bool) – Specifies that share snapshot be returned in the response.

Keyword Arguments:
Returns:

An iterable (auto-paging) of ShareProperties.

Return type:

AsyncItemPaged[ShareProperties]

Example:

List shares in the file share service.
# List the shares in the file service
my_shares = []
async for s in file_service.list_shares():
    my_shares.append(s)

# Print the shares
for share in my_shares:
    print(share)
async set_service_properties(hour_metrics: Metrics | None = None, minute_metrics: Metrics | None = None, cors: List[CorsRule] | None = None, protocol: ShareProtocolSettings | None = None, **kwargs: Any) None[source]

Sets the properties of a storage account’s File Share service, including Azure Storage Analytics. If an element (e.g. hour_metrics) is left as None, the existing settings on the service for that functionality are preserved.

Parameters:
  • hour_metrics (Metrics) – The hour metrics settings provide a summary of request statistics grouped by API in hourly aggregates for files.

  • minute_metrics (Metrics) – The minute metrics settings provide request statistics for each minute for files.

  • cors (list[CorsRule]) – 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.

  • protocol (ShareProtocolSettings) – Sets protocol settings

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Return type:

None

Example:

Sets file share service properties.
# Create service properties
from azure.storage.fileshare import Metrics, CorsRule, RetentionPolicy

# 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_rule1 = CorsRule(['www.xyz.com'], ['GET'])
allowed_origins = ['www.xyz.com', "www.ab.com", "www.bc.com"]
allowed_methods = ['GET', 'PUT']
max_age_in_seconds = 500
exposed_headers = ["x-ms-meta-data*", "x-ms-meta-source*", "x-ms-meta-abc", "x-ms-meta-bcd"]
allowed_headers = ["x-ms-meta-data*", "x-ms-meta-target*", "x-ms-meta-xyz", "x-ms-meta-foo"]
cors_rule2 = CorsRule(
    allowed_origins,
    allowed_methods,
    max_age_in_seconds=max_age_in_seconds,
    exposed_headers=exposed_headers,
    allowed_headers=allowed_headers)

cors = [cors_rule1, cors_rule2]

async with file_service:
    # Set the service properties
    await file_service.set_service_properties(hour_metrics, minute_metrics, cors)
async undelete_share(deleted_share_name: str, deleted_share_version: str, **kwargs: Any) ShareClient[source]

Restores soft-deleted share.

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

Added in version 12.2.0: This operation was introduced in API version ‘2019-12-12’.

Parameters:
  • deleted_share_name (str) – Specifies the name of the deleted share to restore.

  • deleted_share_version (str) – Specifies the version of the deleted share to restore.

Keyword Arguments:

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-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A ShareClient for the undeleted Share.

Return type:

ShareClient

property api_version

The version of the Storage API used for requests.

Return type:

str

property location_mode

The location mode that the client is currently using.

By default this will be “primary”. Options include “primary” and “secondary”.

Return type:

str

property primary_endpoint

The full primary endpoint URL.

Return type:

str

property primary_hostname

The hostname of the primary endpoint.

Return type:

str

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

Return type:

str

Raises:

ValueError

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

Return type:

Optional[str]

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

Return type:

str