azure.storage.fileshare package

class azure.storage.fileshare.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.

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

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

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]

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

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 number of handles closed (this may be 0 if the specified handle was not found).

Return type

int

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)
my_allocated_file.create_file(size=100)
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.
my_file.delete_file()
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 = my_file.download_file()
    data.write(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

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

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

ItemPaged[HandleItem]

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]

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)

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)

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 – 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
destination_file.start_copy_from_url(source_url=source_url)
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.

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

Example:

Upload a file.
with open(SOURCE_FILE, "rb") as source:
    my_file.upload_file(source)
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]

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

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

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

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

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.
my_directory.create_directory()
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
parent_dir.create_directory()

# Create a subdirectory
subdir = parent_dir.create_subdirectory("subdir")
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.
my_directory.delete_directory()
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
my_directory.delete_file(file_name="sample")
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.
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

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 – 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")
parent.create_directory()

# Get a subdirectory client and create the subdirectory "dir1/dir2"
subdirectory = parent.get_subdirectory_client("dir2")
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

ItemPaged[DirectoryProperties and FileProperties]

Example:

List directories and files.
# List the directories and files under the parent directory
my_list = list(parent_dir.list_directories_and_files())
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

ItemPaged[HandleItem]

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)

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)

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:
    my_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.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.

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

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 – Name-value pairs associated with the directory as metadata.

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

Returns

ShareDirectoryClient

Return type

ShareDirectoryClient

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

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.
share.create_share()
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.
share.create_snapshot()
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.
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

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

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]

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 = share.get_share_properties()
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 = share.create_directory("mydir")

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

# List files in the directory
my_files = list(share.list_directories_and_files(directory_name="mydir"))
print(my_files)
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)

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'}
share.set_share_metadata(metadata=data)
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
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.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.

  • 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 import ShareServiceClient
share_service_client = ShareServiceClient(
    account_url=self.account_url,
    credential=self.access_key
)
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.
file_service.create_share(share_name="fileshare1")
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.
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)
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 = 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 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

ItemPaged[ShareProperties]

Example:

List shares in the file share service.
# List the shares in the file service
my_shares = list(file_service.list_shares())

# Print the shares
for share in my_shares:
    print(share)
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]

# Set the service properties
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().

class azure.storage.fileshare.ExponentialRetry(initial_backoff=15, increment_base=3, retry_total=3, retry_to_secondary=False, random_jitter_range=3, **kwargs)[source]

Exponential retry.

Constructs an Exponential retry object. The initial_backoff is used for the first retry. Subsequent retries are retried after initial_backoff + increment_power^retry_count seconds. For example, by default the first retry occurs after 15 seconds, the second after (15+3^1) = 18 seconds, and the third after (15+3^2) = 24 seconds.

Parameters
  • initial_backoff (int) – The initial backoff interval, in seconds, for the first retry.

  • increment_base (int) – The base, in seconds, to increment the initial_backoff by after the first retry.

  • max_attempts (int) – The maximum number of retry attempts.

  • retry_to_secondary (bool) – Whether the request should be retried to secondary, if able. This should only be enabled of RA-GRS accounts are used and potentially stale data can be handled.

  • random_jitter_range (int) – A number in seconds which indicates a range to jitter/randomize for the back-off interval. For example, a random_jitter_range of 3 results in the back-off interval x to vary between x+3 and x-3.

configure_retries(request)
get_backoff_time(settings)[source]

Calculates how long to sleep before retrying.

Returns

An integer indicating how long to wait before retrying the request, or None to indicate no retry should be performed.

Return type

int or None

increment(settings, request, response=None, error=None)

Increment the retry counters.

Parameters
  • response – A pipeline response object.

  • error – An error encountered during the request, or None if the response was received successfully.

Returns

Whether the retry attempts are exhausted.

send(request)

Abstract send method for a synchronous pipeline. Mutates the request.

Context content is dependent on the HttpTransport.

Parameters

request (PipelineRequest) – The pipeline request object

Returns

The pipeline response object.

Return type

PipelineResponse

sleep(settings, transport)
class azure.storage.fileshare.LinearRetry(backoff=15, retry_total=3, retry_to_secondary=False, random_jitter_range=3, **kwargs)[source]

Linear retry.

Constructs a Linear retry object.

Parameters
  • backoff (int) – The backoff interval, in seconds, between retries.

  • max_attempts (int) – The maximum number of retry attempts.

  • retry_to_secondary (bool) – Whether the request should be retried to secondary, if able. This should only be enabled of RA-GRS accounts are used and potentially stale data can be handled.

  • random_jitter_range (int) – A number in seconds which indicates a range to jitter/randomize for the back-off interval. For example, a random_jitter_range of 3 results in the back-off interval x to vary between x+3 and x-3.

configure_retries(request)
get_backoff_time(settings)[source]

Calculates how long to sleep before retrying.

Returns

An integer indicating how long to wait before retrying the request, or None to indicate no retry should be performed.

Return type

int or None

increment(settings, request, response=None, error=None)

Increment the retry counters.

Parameters
  • response – A pipeline response object.

  • error – An error encountered during the request, or None if the response was received successfully.

Returns

Whether the retry attempts are exhausted.

send(request)

Abstract send method for a synchronous pipeline. Mutates the request.

Context content is dependent on the HttpTransport.

Parameters

request (PipelineRequest) – The pipeline request object

Returns

The pipeline response object.

Return type

PipelineResponse

sleep(settings, transport)
class azure.storage.fileshare.LocationMode[source]

Specifies the location the request should be sent to. This mode only applies for RA-GRS accounts which allow secondary read access. All other account types must use PRIMARY.

PRIMARY = 'primary'

Requests should be sent to the primary location.

SECONDARY = 'secondary'

Requests should be sent to the secondary location, if possible.

class azure.storage.fileshare.ResourceTypes(service=False, container=False, object=False)[source]

Specifies the resource types that are accessible with the account SAS.

Parameters
  • service (bool) – Access to service-level APIs (e.g., Get/Set Service Properties, Get Service Stats, List Containers/Queues/Shares)

  • container (bool) – Access to container-level APIs (e.g., Create/Delete Container, Create/Delete Queue, Create/Delete Share, List Blobs/Files and Directories)

  • object (bool) – Access to object-level APIs for blobs, queue messages, and files(e.g. Put Blob, Query Entity, Get Messages, Create File, etc.)

classmethod from_string(string)[source]

Create a ResourceTypes from a string.

To specify service, container, or object you need only to include the first letter of the word in the string. E.g. service and container, you would provide a string “sc”.

Parameters

string (str) – Specify service, container, or object in in the string with the first letter of the word.

Returns

A ResourceTypes object

Return type

ResourceTypes

class azure.storage.fileshare.AccountSasPermissions(read=False, write=False, delete=False, list=False, add=False, create=False, update=False, process=False)[source]

ResourceTypes class to be used with generate_account_sas function and for the AccessPolicies used with set_*_acl. There are two types of SAS which may be used to grant resource access. One is to grant access to a specific resource (resource-specific). Another is to grant access to the entire service for a specific account and allow certain operations based on perms found here.

Parameters
  • read (bool) – Valid for all signed resources types (Service, Container, and Object). Permits read permissions to the specified resource type.

  • write (bool) – Valid for all signed resources types (Service, Container, and Object). Permits write permissions to the specified resource type.

  • delete (bool) – Valid for Container and Object resource types, except for queue messages.

  • list (bool) – Valid for Service and Container resource types only.

  • add (bool) – Valid for the following Object resource types only: queue messages, and append blobs.

  • create (bool) – Valid for the following Object resource types only: blobs and files. Users can create new blobs or files, but may not overwrite existing blobs or files.

  • update (bool) – Valid for the following Object resource types only: queue messages.

  • process (bool) – Valid for the following Object resource type only: queue messages.

classmethod from_string(permission)[source]

Create AccountSasPermissions from a string.

To specify read, write, delete, etc. permissions you need only to include the first letter of the word in the string. E.g. for read and write permissions you would provide a string “rw”.

Parameters

permission (str) – Specify permissions in the string with the first letter of the word.

Returns

An AccountSasPermissions object

Return type

AccountSasPermissions

class azure.storage.fileshare.StorageErrorCode[source]

An enumeration.

account_already_exists = 'AccountAlreadyExists'
account_being_created = 'AccountBeingCreated'
account_is_disabled = 'AccountIsDisabled'
append_position_condition_not_met = 'AppendPositionConditionNotMet'
authentication_failed = 'AuthenticationFailed'
authorization_failure = 'AuthorizationFailure'
blob_already_exists = 'BlobAlreadyExists'
blob_archived = 'BlobArchived'
blob_being_rehydrated = 'BlobBeingRehydrated'
blob_not_archived = 'BlobNotArchived'
blob_not_found = 'BlobNotFound'
blob_overwritten = 'BlobOverwritten'
blob_tier_inadequate_for_content_length = 'BlobTierInadequateForContentLength'
block_count_exceeds_limit = 'BlockCountExceedsLimit'
block_list_too_long = 'BlockListTooLong'
cannot_change_to_lower_tier = 'CannotChangeToLowerTier'
cannot_delete_file_or_directory = 'CannotDeleteFileOrDirectory'
cannot_verify_copy_source = 'CannotVerifyCopySource'
client_cache_flush_delay = 'ClientCacheFlushDelay'
condition_headers_not_supported = 'ConditionHeadersNotSupported'
condition_not_met = 'ConditionNotMet'
container_already_exists = 'ContainerAlreadyExists'
container_being_deleted = 'ContainerBeingDeleted'
container_disabled = 'ContainerDisabled'
container_not_found = 'ContainerNotFound'
container_quota_downgrade_not_allowed = 'ContainerQuotaDowngradeNotAllowed'
content_length_larger_than_tier_limit = 'ContentLengthLargerThanTierLimit'
copy_across_accounts_not_supported = 'CopyAcrossAccountsNotSupported'
copy_id_mismatch = 'CopyIdMismatch'
delete_pending = 'DeletePending'
directory_not_empty = 'DirectoryNotEmpty'
empty_metadata_key = 'EmptyMetadataKey'
feature_version_mismatch = 'FeatureVersionMismatch'
file_lock_conflict = 'FileLockConflict'
incremental_copy_blob_mismatch = 'IncrementalCopyBlobMismatch'
incremental_copy_of_eralier_version_snapshot_not_allowed = 'IncrementalCopyOfEralierVersionSnapshotNotAllowed'
incremental_copy_source_must_be_snapshot = 'IncrementalCopySourceMustBeSnapshot'
infinite_lease_duration_required = 'InfiniteLeaseDurationRequired'
insufficient_account_permissions = 'InsufficientAccountPermissions'
internal_error = 'InternalError'
invalid_authentication_info = 'InvalidAuthenticationInfo'
invalid_blob_or_block = 'InvalidBlobOrBlock'
invalid_blob_tier = 'InvalidBlobTier'
invalid_blob_type = 'InvalidBlobType'
invalid_block_id = 'InvalidBlockId'
invalid_block_list = 'InvalidBlockList'
invalid_file_or_directory_path_name = 'InvalidFileOrDirectoryPathName'
invalid_header_value = 'InvalidHeaderValue'
invalid_http_verb = 'InvalidHttpVerb'
invalid_input = 'InvalidInput'
invalid_marker = 'InvalidMarker'
invalid_md5 = 'InvalidMd5'
invalid_metadata = 'InvalidMetadata'
invalid_operation = 'InvalidOperation'
invalid_page_range = 'InvalidPageRange'
invalid_query_parameter_value = 'InvalidQueryParameterValue'
invalid_range = 'InvalidRange'
invalid_resource_name = 'InvalidResourceName'
invalid_source_blob_type = 'InvalidSourceBlobType'
invalid_source_blob_url = 'InvalidSourceBlobUrl'
invalid_uri = 'InvalidUri'
invalid_version_for_page_blob_operation = 'InvalidVersionForPageBlobOperation'
invalid_xml_document = 'InvalidXmlDocument'
invalid_xml_node_value = 'InvalidXmlNodeValue'
lease_already_broken = 'LeaseAlreadyBroken'
lease_already_present = 'LeaseAlreadyPresent'
lease_id_mismatch_with_blob_operation = 'LeaseIdMismatchWithBlobOperation'
lease_id_mismatch_with_container_operation = 'LeaseIdMismatchWithContainerOperation'
lease_id_mismatch_with_lease_operation = 'LeaseIdMismatchWithLeaseOperation'
lease_id_missing = 'LeaseIdMissing'
lease_is_breaking_and_cannot_be_acquired = 'LeaseIsBreakingAndCannotBeAcquired'
lease_is_breaking_and_cannot_be_changed = 'LeaseIsBreakingAndCannotBeChanged'
lease_is_broken_and_cannot_be_renewed = 'LeaseIsBrokenAndCannotBeRenewed'
lease_lost = 'LeaseLost'
lease_not_present_with_blob_operation = 'LeaseNotPresentWithBlobOperation'
lease_not_present_with_container_operation = 'LeaseNotPresentWithContainerOperation'
lease_not_present_with_lease_operation = 'LeaseNotPresentWithLeaseOperation'
max_blob_size_condition_not_met = 'MaxBlobSizeConditionNotMet'
md5_mismatch = 'Md5Mismatch'
message_not_found = 'MessageNotFound'
message_too_large = 'MessageTooLarge'
metadata_too_large = 'MetadataTooLarge'
missing_content_length_header = 'MissingContentLengthHeader'
missing_required_header = 'MissingRequiredHeader'
missing_required_query_parameter = 'MissingRequiredQueryParameter'
missing_required_xml_node = 'MissingRequiredXmlNode'
multiple_condition_headers_not_supported = 'MultipleConditionHeadersNotSupported'
no_pending_copy_operation = 'NoPendingCopyOperation'
operation_not_allowed_on_incremental_copy_blob = 'OperationNotAllowedOnIncrementalCopyBlob'
operation_timed_out = 'OperationTimedOut'
out_of_range_input = 'OutOfRangeInput'
out_of_range_query_parameter_value = 'OutOfRangeQueryParameterValue'
parent_not_found = 'ParentNotFound'
pending_copy_operation = 'PendingCopyOperation'
pop_receipt_mismatch = 'PopReceiptMismatch'
previous_snapshot_cannot_be_newer = 'PreviousSnapshotCannotBeNewer'
previous_snapshot_not_found = 'PreviousSnapshotNotFound'
previous_snapshot_operation_not_supported = 'PreviousSnapshotOperationNotSupported'
queue_already_exists = 'QueueAlreadyExists'
queue_being_deleted = 'QueueBeingDeleted'
queue_disabled = 'QueueDisabled'
queue_not_empty = 'QueueNotEmpty'
queue_not_found = 'QueueNotFound'
read_only_attribute = 'ReadOnlyAttribute'
request_body_too_large = 'RequestBodyTooLarge'
request_url_failed_to_parse = 'RequestUrlFailedToParse'
resource_already_exists = 'ResourceAlreadyExists'
resource_not_found = 'ResourceNotFound'
resource_type_mismatch = 'ResourceTypeMismatch'
sequence_number_condition_not_met = 'SequenceNumberConditionNotMet'
sequence_number_increment_too_large = 'SequenceNumberIncrementTooLarge'
server_busy = 'ServerBusy'
share_already_exists = 'ShareAlreadyExists'
share_being_deleted = 'ShareBeingDeleted'
share_disabled = 'ShareDisabled'
share_has_snapshots = 'ShareHasSnapshots'
share_not_found = 'ShareNotFound'
share_snapshot_count_exceeded = 'ShareSnapshotCountExceeded'
share_snapshot_in_progress = 'ShareSnapshotInProgress'
share_snapshot_operation_not_supported = 'ShareSnapshotOperationNotSupported'
sharing_violation = 'SharingViolation'
snaphot_operation_rate_exceeded = 'SnaphotOperationRateExceeded'
snapshot_count_exceeded = 'SnapshotCountExceeded'
snapshots_present = 'SnapshotsPresent'
source_condition_not_met = 'SourceConditionNotMet'
system_in_use = 'SystemInUse'
target_condition_not_met = 'TargetConditionNotMet'
unauthorized_blob_overwrite = 'UnauthorizedBlobOverwrite'
unsupported_header = 'UnsupportedHeader'
unsupported_http_verb = 'UnsupportedHttpVerb'
unsupported_query_parameter = 'UnsupportedQueryParameter'
unsupported_xml_node = 'UnsupportedXmlNode'
class azure.storage.fileshare.Metrics(**kwargs)[source]

A summary of request statistics grouped by API in hour or minute aggregates for files.

All required parameters must be populated in order to send to Azure.

Keyword Arguments
  • version (str) – The version of Storage Analytics to configure.

  • enabled (bool) – Required. Indicates whether metrics are enabled for the File service.

  • include_ap_is (bool) – Indicates whether metrics should generate summary statistics for called API operations.

  • retention_policy (RetentionPolicy) – Determines how long the associated data should persist.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionaly use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

validate()

Validate this model recursively and return a list of ValidationError.

Returns

A list of validation error

Return type

list

class azure.storage.fileshare.RetentionPolicy(enabled=False, days=None)[source]

The retention policy which determines how long the associated data should persist.

All required parameters must be populated in order to send to Azure.

Parameters
  • enabled (bool) – Required. Indicates whether a retention policy is enabled for the storage service.

  • days (int) – Indicates the number of days that metrics or logging or soft-deleted data should be retained. All data older than this value will be deleted.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionaly use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

validate()

Validate this model recursively and return a list of ValidationError.

Returns

A list of validation error

Return type

list

class azure.storage.fileshare.CorsRule(allowed_origins, allowed_methods, **kwargs)[source]

CORS is an HTTP feature that enables a web application running under one domain to access resources in another domain. Web browsers implement a security restriction known as same-origin policy that prevents a web page from calling APIs in a different domain; CORS provides a secure way to allow one domain (the origin domain) to call APIs in another domain.

All required parameters must be populated in order to send to Azure.

Parameters
  • allowed_origins (list(str)) – A list of origin domains that will be allowed via CORS, or “*” to allow all domains. The list of must contain at least one entry. Limited to 64 origin domains. Each allowed origin can have up to 256 characters.

  • allowed_methods (list(str)) – A list of HTTP methods that are allowed to be executed by the origin. The list of must contain at least one entry. For Azure Storage, permitted methods are DELETE, GET, HEAD, MERGE, POST, OPTIONS or PUT.

Keyword Arguments
  • allowed_headers (list(str)) – Defaults to an empty list. A list of headers allowed to be part of the cross-origin request. Limited to 64 defined headers and 2 prefixed headers. Each header can be up to 256 characters.

  • exposed_headers (list(str)) – Defaults to an empty list. A list of response headers to expose to CORS clients. Limited to 64 defined headers and two prefixed headers. Each header can be up to 256 characters.

  • max_age_in_seconds (int) – The number of seconds that the client/browser should cache a preflight response.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionaly use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

validate()

Validate this model recursively and return a list of ValidationError.

Returns

A list of validation error

Return type

list

class azure.storage.fileshare.AccessPolicy(permission=None, expiry=None, start=None)[source]

Access Policy class used by the set and get acl methods in each service.

A stored access policy can specify the start time, expiry time, and permissions for the Shared Access Signatures with which it’s associated. Depending on how you want to control access to your resource, you can specify all of these parameters within the stored access policy, and omit them from the URL for the Shared Access Signature. Doing so permits you to modify the associated signature’s behavior at any time, as well as to revoke it. Or you can specify one or more of the access policy parameters within the stored access policy, and the others on the URL. Finally, you can specify all of the parameters on the URL. In this case, you can use the stored access policy to revoke the signature, but not to modify its behavior.

Together the Shared Access Signature and the stored access policy must include all fields required to authenticate the signature. If any required fields are missing, the request will fail. Likewise, if a field is specified both in the Shared Access Signature URL and in the stored access policy, the request will fail with status code 400 (Bad Request).

Parameters
  • permission (str or FileSasPermissions or ShareSasPermissions) – The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy.

  • expiry (datetime or str) – The time at which the shared access signature becomes invalid. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC.

  • start (datetime or str) – The time at which the shared access signature becomes valid. If omitted, start time for this call is assumed to be the time when the storage service receives the request. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionaly use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

validate()

Validate this model recursively and return a list of ValidationError.

Returns

A list of validation error

Return type

list

class azure.storage.fileshare.FileSasPermissions(read=False, create=False, write=False, delete=False)[source]

FileSasPermissions class to be used with generating shared access signature operations.

Parameters
  • read (bool) – Read the content, properties, metadata. Use the file as the source of a copy operation.

  • create (bool) – Create a new file or copy a file to a new file.

  • write (bool) – Create or write content, properties, metadata. Resize the file. Use the file as the destination of a copy operation within the same account.

  • delete (bool) – Delete the file.

classmethod from_string(permission)[source]

Create a FileSasPermissions from a string.

To specify read, create, write, or delete permissions you need only to include the first letter of the word in the string. E.g. For read and create permissions, you would provide a string “rc”.

Parameters

permission (str) – The string which dictates the read, create, write, or delete permissions

Returns

A FileSasPermissions object

Return type

FileSasPermissions

class azure.storage.fileshare.ShareSasPermissions(read=False, write=False, delete=False, list=False)[source]

ShareSasPermissions class to be used to be used with generating shared access signature and access policy operations.

Parameters
  • read (bool) – Read the content, properties or metadata of any file in the share. Use any file in the share as the source of a copy operation.

  • write (bool) – For any file in the share, create or write content, properties or metadata. Resize the file. Use the file as the destination of a copy operation within the same account. Note: You cannot grant permissions to read or write share properties or metadata with a service SAS. Use an account SAS instead.

  • delete (bool) – Delete any file in the share. Note: You cannot grant permissions to delete a share with a service SAS. Use an account SAS instead.

  • list (bool) – List files and directories in the share.

classmethod from_string(permission)[source]

Create a ShareSasPermissions from a string.

To specify read, write, delete, or list permissions you need only to include the first letter of the word in the string. E.g. For read and write permissions, you would provide a string “rw”.

Parameters

permission (str) – The string which dictates the read, write, delete, or list permissions

Returns

A ShareSasPermissions object

Return type

ShareSasPermissions

class azure.storage.fileshare.ShareProperties(**kwargs)[source]

Share’s properties class.

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

  • last_modified (datetime) – A datetime object representing the last time the share was modified.

  • etag (str) – The ETag contains a value that you can use to perform operations conditionally.

  • quota (int) – The allocated quota.

  • metadata (dict) – A dict with name_value pairs to associate with the share as metadata.

  • snapshot (str) – Snapshot of the share.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.storage.fileshare.DirectoryProperties(**kwargs)[source]

Directory’s properties class.

Variables
  • name (str) – The name of the directory.

  • last_modified (datetime) – A datetime object representing the last time the directory was modified.

  • etag (str) – The ETag contains a value that you can use to perform operations conditionally.

  • server_encrypted (bool) – Whether encryption is enabled.

  • change_time (str or datetime) – Change time for the file.

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

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

  • file_attributes (str or NTFSAttributes) – The file system attributes for files and directories.

  • permission_key (str) – Key of the permission to be set for the directory/file.

  • file_id (str) – Required. FileId uniquely identifies the file or directory.

  • parent_id (str) – ParentId uniquely identifies the parent directory of the object.

Keyword Arguments

metadata (dict) – A dict with name_value pairs to associate with the directory as metadata.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.storage.fileshare.FileProperties(**kwargs)[source]

File’s properties class.

Variables
  • name (str) – The name of the file.

  • path (str) – The path of the file.

  • share (str) – The name of share.

  • snapshot (str) – File snapshot.

  • content_length (int) – Size of file in bytes.

  • metadata (dict) – A dict with name_value pairs to associate with the file as metadata.

  • file_type (str) – Type of the file.

  • last_modified (datetime) – A datetime object representing the last time the file was modified.

  • etag (str) – The ETag contains a value that you can use to perform operations conditionally.

  • size (int) – Size of file in bytes.

  • content_range (str) – The range of bytes.

  • server_encrypted (bool) – Whether encryption is enabled.

  • copy (CopyProperties) – The copy properties.

  • content_settings (ContentSettings) – The content settings for the file.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.storage.fileshare.ContentSettings(content_type=None, content_encoding=None, content_language=None, content_disposition=None, cache_control=None, content_md5=None, **kwargs)[source]

Used to store the content settings of a file.

Parameters
  • content_type (str) – The content type specified for the file. If no content type was specified, the default content type is application/octet-stream.

  • content_encoding (str) – If the content_encoding has previously been set for the file, that value is stored.

  • content_language (str) – If the content_language has previously been set for the file, that value is stored.

  • content_disposition (str) – content_disposition conveys additional information about how to process the response payload, and also can be used to attach additional metadata. If content_disposition has previously been set for the file, that value is stored.

  • cache_control (str) – If the cache_control has previously been set for the file, that value is stored.

  • content_md5 (str) – If the content_md5 has been set for the file, this response header is stored so that the client can check for message content integrity.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.storage.fileshare.Handle(**kwargs)[source]

A listed Azure Storage handle item.

All required parameters must be populated in order to send to Azure.

Keyword Arguments
  • handle_id (str) – Required. XSMB service handle ID

  • path (str) – Required. File or directory name including full path starting from share root

  • file_id (str) – Required. FileId uniquely identifies the file or directory.

  • parent_id (str) – ParentId uniquely identifies the parent directory of the object.

  • session_id (str) – Required. SMB session ID in context of which the file handle was opened

  • client_ip (str) – Required. Client IP that opened the handle

  • open_time (datetime) – Required. Time when the session that previously opened the handle has last been reconnected. (UTC)

  • last_reconnect_time (datetime) – Time handle was last connected to (UTC)

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.storage.fileshare.NTFSAttributes(read_only=False, hidden=False, system=False, none=False, directory=False, archive=False, temporary=False, offline=False, not_content_indexed=False, no_scrub_data=False)[source]

Valid set of attributes to set for file or directory. To set attribute for directory, ‘Directory’ should always be enabled except setting ‘None’ for directory.

Variables
  • read_only (bool) – Enable/disable ‘ReadOnly’ attribute for DIRECTORY or FILE

  • hidden (bool) – Enable/disable ‘Hidden’ attribute for DIRECTORY or FILE

  • system (bool) – Enable/disable ‘System’ attribute for DIRECTORY or FILE

  • none (bool) – Enable/disable ‘None’ attribute for DIRECTORY or FILE to clear all attributes of FILE/DIRECTORY

  • directory (bool) – Enable/disable ‘Directory’ attribute for DIRECTORY

  • archive (bool) – Enable/disable ‘Archive’ attribute for DIRECTORY or FILE

  • temporary (bool) – Enable/disable ‘Temporary’ attribute for FILE

  • offline (bool) – Enable/disable ‘Offline’ attribute for DIRECTORY or FILE

  • not_content_indexed (bool) – Enable/disable ‘NotContentIndexed’ attribute for DIRECTORY or FILE

  • no_scrub_data (bool) – Enable/disable ‘NoScrubData’ attribute for DIRECTORY or FILE

classmethod from_string(string)[source]

Create a NTFSAttributes from a string.

To specify permissions you can pass in a string with the desired permissions, e.g. “ReadOnly|Hidden|System”

Parameters

string (str) – The string which dictates the permissions.

Returns

A NTFSAttributes object

Return type

NTFSAttributes

class azure.storage.fileshare.HandleItem(*, handle_id: str, path: str, file_id: str, session_id: str, client_ip: str, open_time, parent_id: str = None, last_reconnect_time=None, **kwargs)[source]

A listed Azure Storage handle item.

All required parameters must be populated in order to send to Azure.

Parameters
  • handle_id (str) – Required. XSMB service handle ID

  • path (str) – Required. File or directory name including full path starting from share root

  • file_id (str) – Required. FileId uniquely identifies the file or directory.

  • parent_id (str) – ParentId uniquely identifies the parent directory of the object.

  • session_id (str) – Required. SMB session ID in context of which the file handle was opened

  • client_ip (str) – Required. Client IP that opened the handle

  • open_time (datetime) – Required. Time when the session that previously opened the handle has last been reconnected. (UTC)

  • last_reconnect_time (datetime) – Time handle was last connected to (UTC)

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionaly use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

validate()

Validate this model recursively and return a list of ValidationError.

Returns

A list of validation error

Return type

list

azure.storage.fileshare.generate_account_sas(account_name, account_key, resource_types, permission, expiry, start=None, ip=None, **kwargs)[source]

Generates a shared access signature for the file service.

Use the returned signature with the credential parameter of any ShareServiceClient, ShareClient, ShareDirectoryClient, or ShareFileClient.

Parameters
  • account_name (str) – The storage account name used to generate the shared access signature.

  • account_key (str) – The account key, also called shared key or access key, to generate the shared access signature.

  • resource_types (ResourceTypes) – Specifies the resource types that are accessible with the account SAS.

  • permission (AccountSasPermissions) – The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy.

  • expiry (datetime or str) – The time at which the shared access signature becomes invalid. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC.

  • start (datetime or str) – The time at which the shared access signature becomes valid. If omitted, start time for this call is assumed to be the time when the storage service receives the request. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC.

  • ip (str) – Specifies an IP address or a range of IP addresses from which to accept requests. If the IP address from which the request originates does not match the IP address or address range specified on the SAS token, the request is not authenticated. For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS restricts the request to those IP addresses.

Keyword Arguments

protocol (str) – Specifies the protocol permitted for a request made. The default value is https.

Returns

A Shared Access Signature (sas) token.

Return type

str

Example:

Generate a sas token.
from azure.storage.fileshare import ShareServiceClient
share_service_client = ShareServiceClient.from_connection_string(self.connection_string)

# Create a SAS token to use to authenticate a new client
from azure.storage.fileshare import generate_account_sas, ResourceTypes, AccountSasPermissions

sas_token = generate_account_sas(
    self.account_name,
    self.access_key,
    resource_types=ResourceTypes(service=True),
    permission=AccountSasPermissions(read=True),
    expiry=datetime.utcnow() + timedelta(hours=1)
)
azure.storage.fileshare.generate_share_sas(account_name, share_name, account_key, permission=None, expiry=None, start=None, policy_id=None, ip=None, **kwargs)[source]

Generates a shared access signature for a share.

Use the returned signature with the credential parameter of any ShareServiceClient, ShareClient, ShareDirectoryClient, or ShareFileClient.

Parameters
  • account_name (str) – The storage account name used to generate the shared access signature.

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

  • account_key (str) – The account key, also called shared key or access key, to generate the shared access signature.

  • permission (ShareSasPermissions) – The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions. Permissions must be ordered read, create, write, delete, list. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy.

  • expiry (datetime or str) – The time at which the shared access signature becomes invalid. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC.

  • start (datetime or str) – The time at which the shared access signature becomes valid. If omitted, start time for this call is assumed to be the time when the storage service receives the request. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC.

  • policy_id (str) – A unique value up to 64 characters in length that correlates to a stored access policy. To create a stored access policy, use set_share_access_policy().

  • ip (str) – Specifies an IP address or a range of IP addresses from which to accept requests. If the IP address from which the request originates does not match the IP address or address range specified on the SAS token, the request is not authenticated. For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS restricts the request to those IP addresses.

Keyword Arguments
  • cache_control (str) – Response header value for Cache-Control when resource is accessed using this shared access signature.

  • content_disposition (str) – Response header value for Content-Disposition when resource is accessed using this shared access signature.

  • content_encoding (str) – Response header value for Content-Encoding when resource is accessed using this shared access signature.

  • content_language (str) – Response header value for Content-Language when resource is accessed using this shared access signature.

  • content_type (str) – Response header value for Content-Type when resource is accessed using this shared access signature.

  • protocol (str) – Specifies the protocol permitted for a request made. The default value is https.

Returns

A Shared Access Signature (sas) token.

Return type

str

azure.storage.fileshare.generate_file_sas(account_name, share_name, file_path, account_key, permission=None, expiry=None, start=None, policy_id=None, ip=None, **kwargs)[source]

Generates a shared access signature for a file.

Use the returned signature with the credential parameter of any ShareServiceClient, ShareClient, ShareDirectoryClient, or ShareFileClient.

Parameters
  • account_name (str) – The storage account name used to generate the shared access signature.

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

  • file_path (List[str]) – The file path represented as a list of path segments, including the file name.

  • account_key (str) – The account key, also called shared key or access key, to generate the shared access signature.

  • permission (FileSasPermissions) – The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions. Permissions must be ordered read, write, delete, list. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy.

  • expiry (datetime or str) – The time at which the shared access signature becomes invalid. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC.

  • start (datetime or str) – The time at which the shared access signature becomes valid. If omitted, start time for this call is assumed to be the time when the storage service receives the request. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC.

  • policy_id (str) – A unique value up to 64 characters in length that correlates to a stored access policy.

  • ip (str) – Specifies an IP address or a range of IP addresses from which to accept requests. If the IP address from which the request originates does not match the IP address or address range specified on the SAS token, the request is not authenticated. For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS restricts the request to those IP addresses.

Keyword Arguments
  • cache_control (str) – Response header value for Cache-Control when resource is accessed using this shared access signature.

  • content_disposition (str) – Response header value for Content-Disposition when resource is accessed using this shared access signature.

  • content_encoding (str) – Response header value for Content-Encoding when resource is accessed using this shared access signature.

  • content_language (str) – Response header value for Content-Language when resource is accessed using this shared access signature.

  • content_type (str) – Response header value for Content-Type when resource is accessed using this shared access signature.

  • protocol (str) – Specifies the protocol permitted for a request made. The default value is https.

Returns

A Shared Access Signature (sas) token.

Return type

str