azure.storage.fileshare.aio package

class azure.storage.fileshare.aio.ShareFileClient(account_url, share_name, file_path, snapshot=None, credential=None, **kwargs)[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 – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

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

  • loop – The event loop to run the asynchronous tasks.

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

async abort_copy(copy_id, **kwargs)[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

timeout (int) – The timeout parameter is expressed in seconds.

Return type

None

async clear_range(offset, length, **kwargs)[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

timeout (int) – The timeout parameter is expressed in seconds.

Returns

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

Return type

Dict[str, Any]

async close_all_handles(**kwargs)[source]

Close any open file handles.

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

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Returns

The total number of handles closed.

Return type

int

async close_handle(handle, **kwargs)[source]

Close an open file handle.

Parameters

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

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Returns

The total number of handles closed. This could be 0 if the supplied handle was not found.

Return type

int

async create_file(size, file_attributes='none', file_creation_time='now', file_last_write_time='now', file_permission=None, permission_key=None, **kwargs)[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) – 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) – Creation time for the file Default value: Now.

  • file_last_write_time (str or datetime) – Last write time for the file Default value: Now.

  • 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
  • content_settings (ContentSettings) – ContentSettings object used to set file properties. Used to set content type, encoding, language, disposition, md5, and cache control.

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

  • timeout (int) – The timeout parameter is expressed in seconds.

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)
async delete_file(**kwargs)[source]

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

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Return type

None

Example:

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

Downloads a file to a stream with automatic chunking.

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.

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

  • timeout (int) – The timeout parameter is expressed in seconds.

Returns

A iterable data generator (stream)

Example:

Download a file.
with open(DEST_FILE, "wb") as data:
    stream = await my_file.download_file()
    data.write(await stream.readall())
classmethod from_connection_string(conn_str, share_name, file_path, snapshot=None, credential=None, **kwargs)[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 – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

Returns

A File client.

Return type

ShareFileClient

Example:

Creates the file client with connection string.
from azure.storage.fileshare import ShareFileClient
file = ShareFileClient.from_connection_string(
    self.connection_string,
    share_name="helloworld2",
    file_path="myfile")
classmethod from_file_url(file_url, snapshot=None, credential=None, **kwargs)[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 – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

Returns

A File client.

Return type

ShareFileClient

async get_file_properties(**kwargs)[source]

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

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Returns

FileProperties

Return type

FileProperties

async get_ranges(offset=None, length=None, **kwargs)[source]

Returns the list of valid ranges 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

timeout (int) – The timeout parameter is expressed in seconds.

Returns

A list of valid ranges.

Return type

List[dict[str, int]]

list_handles(**kwargs)[source]

Lists handles for file.

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Returns

An auto-paging iterable of HandleItem

Return type

AsyncItemPaged[HandleItem]

async resize_file(size, **kwargs)[source]

Resizes a file to the specified size.

Parameters

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

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Returns

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

Return type

Dict[str, Any]

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

timeout (int) – The timeout parameter is expressed in seconds.

Returns

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

Return type

dict(str, Any)

async set_http_headers(content_settings, file_attributes='preserve', file_creation_time='preserve', file_last_write_time='preserve', file_permission=None, permission_key=None, **kwargs)[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) – 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) – Creation time for the file Default value: Preserve.

  • file_last_write_time (str or datetime) – Last write time for the file Default value: Preserve.

  • 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

timeout (int) – The timeout parameter is expressed in seconds.

Returns

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

Return type

dict(str, Any)

async start_copy_from_url(source_url, **kwargs)[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
  • metadata (dict(str,str)) – Name-value pairs associated with the file as metadata.

  • timeout (int) – The timeout parameter is expressed in seconds.

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, length=None, file_attributes='none', file_creation_time='now', file_last_write_time='now', file_permission=None, permission_key=None, **kwargs)[source]

Uploads a new file.

Parameters
  • data (Any) – 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) – 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) – Creation time for the file Default value: Now.

  • file_last_write_time (str or datetime) – Last write time for the file Default value: Now.

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

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

  • timeout (int) – The timeout parameter is expressed in seconds.

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, offset, length, **kwargs)[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.

  • timeout (int) – The timeout parameter is expressed in seconds.

  • 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, offset, length, source_offset, **kwargs)[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

timeout (int) – The timeout parameter is expressed in seconds.

property location_mode

The location mode that the client is currently using.

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

Type

str

property primary_endpoint

The full primary endpoint URL.

Type

str

property primary_hostname

The hostname of the primary endpoint.

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.

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.

Type

str or None

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

class azure.storage.fileshare.aio.ShareDirectoryClient(account_url, share_name, directory_path, snapshot=None, credential=None, **kwargs)[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 – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

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

  • loop – The event loop to run the asynchronous tasks.

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

async close_all_handles(recursive=False, **kwargs)[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) – The timeout parameter is expressed in seconds.

Returns

The total number of handles closed.

Return type

int

async close_handle(handle, **kwargs)[source]

Close an open file handle.

Parameters

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

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Returns

The total number of handles closed. This could be 0 if the supplied handle was not found.

Return type

int

async create_directory(**kwargs)[source]

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

Keyword Arguments
  • metadata (dict(str,str)) – Name-value pairs associated with the directory as metadata.

  • timeout (int) – The timeout parameter is expressed in seconds.

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, **kwargs)[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
  • metadata (dict(str,str)) – Name-value pairs associated with the subdirectory as metadata.

  • timeout (int) – The timeout parameter is expressed in seconds.

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)[source]

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

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Return type

None

Example:

Deletes a directory.
await directory.delete_directory()
async delete_file(file_name, **kwargs)[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) – The timeout parameter is expressed in seconds.

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, **kwargs)[source]

Deletes a subdirectory.

Parameters

directory_name (str) – The name of the subdirectory.

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Return type

None

Example:

Delete a subdirectory.
await parent_dir.delete_subdirectory("subdir")
classmethod from_connection_string(conn_str, share_name, directory_path, credential=None, **kwargs)[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 – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

Returns

A directory client.

Return type

ShareDirectoryClient

classmethod from_directory_url(directory_url, snapshot=None, credential=None, **kwargs)[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 – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

Returns

A directory client.

Return type

ShareDirectoryClient

async get_directory_properties(**kwargs)[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) – The timeout parameter is expressed in seconds.

Returns

DirectoryProperties

Return type

DirectoryProperties

get_file_client(file_name, **kwargs)[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, **kwargs)[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=None, **kwargs)[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

timeout (int) – The timeout parameter is expressed in seconds.

Returns

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

Return type

AsyncItemPaged[DirectoryProperties and 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=False, **kwargs)[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) – The timeout parameter is expressed in seconds.

Returns

An auto-paging iterable of HandleItem

Return type

AsyncItemPaged[HandleItem]

async set_directory_metadata(metadata, **kwargs)[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) – The timeout parameter is expressed in seconds.

Returns

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

Return type

dict(str, Any)

async set_http_headers(file_attributes='none', file_creation_time='preserve', file_last_write_time='preserve', file_permission=None, permission_key=None, **kwargs)[source]

Sets HTTP headers on the directory.

Parameters
  • file_attributes (str or NTFSAttributes) – 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) – Creation time for the file Default value: Preserve.

  • file_last_write_time (str or datetime) – Last write time for the file Default value: Preserve.

  • 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

timeout (int) – The timeout parameter is expressed in seconds.

Returns

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

Return type

dict(str, Any)

async upload_file(file_name, data, length=None, **kwargs)[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 (Any) – Content of the file.

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

Keyword Arguments
  • metadata (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.

  • timeout (int) – The timeout parameter is expressed in seconds.

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

The location mode that the client is currently using.

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

Type

str

property primary_endpoint

The full primary endpoint URL.

Type

str

property primary_hostname

The hostname of the primary endpoint.

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.

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.

Type

str or None

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

class azure.storage.fileshare.aio.ShareClient(account_url, share_name, snapshot=None, credential=None, **kwargs)[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 – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

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

  • loop – The event loop to run the asynchronous tasks.

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

async create_directory(directory_name, **kwargs)[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
  • metadata (dict(str,str)) – Name-value pairs associated with the directory as metadata.

  • timeout (int) – The timeout parameter is expressed in seconds.

Returns

ShareDirectoryClient

Return type

ShareDirectoryClient

async create_permission_for_share(file_permission, **kwargs)[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

timeout (int) – The timeout parameter is expressed in seconds.

Returns

A file permission key

Return type

str

async create_share(**kwargs)[source]

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

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

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

  • timeout (int) – The timeout parameter is expressed in seconds.

Returns

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

Return type

dict(str, Any)

Example:

Creates a file share.
await share.create_share()
async create_snapshot(**kwargs)[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
  • metadata (dict(str,str)) – Name-value pairs associated with the share as metadata.

  • timeout (int) – The timeout parameter is expressed in seconds.

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_share(delete_snapshots=False, **kwargs)[source]

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

Parameters

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

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Return type

None

Example:

Deletes the share and any snapshots.
await share.delete_share(delete_snapshots=True)
classmethod from_connection_string(conn_str, share_name, snapshot=None, credential=None, **kwargs)[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 (str) – The optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from create_snapshot().

  • credential – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

Returns

A share client.

Return type

ShareClient

Example:

Gets the share client from connection string.
from azure.storage.fileshare import ShareClient
share = ShareClient.from_connection_string(self.connection_string, "sharesamples2")
classmethod from_share_url(share_url, snapshot=None, credential=None, **kwargs)[source]
Parameters
  • share_url (str) – The full URI to the share.

  • 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 – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

Returns

A share client.

Return type

ShareClient

get_directory_client(directory_path=None)[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)[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, **kwargs)[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

timeout (int) – The timeout parameter is expressed in seconds.

Returns

A file permission (a portable SDDL)

Return type

str

async get_share_access_policy(**kwargs)[source]

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

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

Returns

Access policy information in a dict.

Return type

dict[str, Any]

async get_share_properties(**kwargs)[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) – The timeout parameter is expressed in seconds.

Returns

The share properties.

Return type

ShareProperties

Example:

Gets the share properties.
properties = await share.get_share_properties()
async get_share_stats(**kwargs)[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) – The timeout parameter is expressed in seconds.

Returns

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

Return type

int

list_directories_and_files(directory_name=None, name_starts_with=None, marker=None, **kwargs)[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

timeout (int) – The timeout parameter is expressed in seconds.

Returns

An auto-paging iterable of dict-like DirectoryProperties and 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, **kwargs)[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) – The timeout parameter is expressed in seconds.

Returns

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

Return type

dict(str, Any)

async set_share_metadata(metadata, **kwargs)[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) – The timeout parameter is expressed in seconds.

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_quota(quota, **kwargs)[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) – The timeout parameter is expressed in seconds.

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 location_mode

The location mode that the client is currently using.

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

Type

str

property primary_endpoint

The full primary endpoint URL.

Type

str

property primary_hostname

The hostname of the primary endpoint.

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.

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.

Type

str or None

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

class azure.storage.fileshare.aio.ShareServiceClient(account_url, credential=None, **kwargs)[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 – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

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

  • loop – The event loop to run the asynchronous tasks.

  • 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
)
async create_share(share_name, **kwargs)[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) – The timeout parameter is expressed in seconds.

Return type

ShareClient

Example:

Create a share in the file share service.
await file_service.create_share(share_name="fileshare1")
async delete_share(share_name, delete_snapshots=False, **kwargs)[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) – The timeout parameter is expressed in seconds.

Return type

None

Example:

Delete a share in the file share service.
await file_service.delete_share(share_name="fileshare1")
classmethod from_connection_string(conn_str, credential=None, **kwargs)[source]

Create ShareServiceClient from a Connection String.

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

  • credential – The credential with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string or an account shared access key.

Returns

A File Share service client.

Return type

ShareServiceClient

Example:

Create the share service client with connection string.
from azure.storage.fileshare import ShareServiceClient
share_service_client = ShareServiceClient.from_connection_string(self.connection_string)
async get_service_properties(**kwargs)[source]

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

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

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

timeout (int) – The timeout parameter is expressed in seconds.

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=None, minute_metrics=None, cors=None, **kwargs)[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.

Keyword Arguments

timeout (int) – The timeout parameter is expressed in seconds.

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)
property location_mode

The location mode that the client is currently using.

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

Type

str

property primary_endpoint

The full primary endpoint URL.

Type

str

property primary_hostname

The hostname of the primary endpoint.

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.

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.

Type

str or None

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