azure.storage.fileshare package

class azure.storage.fileshare.AccessPolicy(permission: ShareSasPermissions | str | None = None, expiry: datetime | str | None = None, start: datetime | str | None = 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. The provided datetime will always be interpreted as UTC.

Keyword Arguments:
  • start (str) – The date-time the policy is active.

  • expiry (str) – The date-time the policy expires.

  • permission (str) – The permissions for the ACL policy.

classmethod deserialize(data: Any, content_type: str | None = None) Self

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

Return type:

Self

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) Self

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

  • key_extractors (function) – A key extractor function.

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

Returns:

An instance of this model

Raises:

DeserializationError – if something went wrong

Return type:

Self

classmethod is_xml_model() bool
as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

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

Advanced usage might optionally 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

If you want XML serialization, you can pass the kwargs is_xml=True.

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

  • key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

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

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

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

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

Returns:

A dict JSON compatible object

Return type:

dict

expiry: datetime | str | None

The time at which the shared access signature becomes invalid.

permission: ShareSasPermissions | str | None

The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions.

start: datetime | str | None

The time at which the shared access signature becomes valid.

class azure.storage.fileshare.AccountSasPermissions(read: bool = False, write: bool = False, delete: bool = False, list: bool = False, add: bool = False, create: bool = False, update: bool = False, process: bool = False, delete_previous_version: bool = False, **kwargs)[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.

  • delete_previous_version (bool) – Delete the previous blob version for the versioning enabled storage account.

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

Keyword Arguments:
  • tag (bool) – To enable set or get tags on the blobs in the container.

  • filter_by_tags (bool) – To enable get blobs by tags, this should be used together with list permission.

  • set_immutability_policy (bool) – To enable operations related to set/delete immutability policy. To get immutability policy, you just need read permission.

  • permanent_delete (bool) – To enable permanent delete on the blob is permitted. Valid for Object resource type of Blob only.

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

add: bool = False
create: bool = False
delete: bool = False
delete_previous_version: bool = False
filter_by_tags: bool = False
list: bool = False
permanent_delete: bool = False
process: bool = False
read: bool = False
set_immutability_policy: bool = False
tag: bool = False
update: bool = False
write: bool = False
class azure.storage.fileshare.ContentSettings(content_type: str | None = None, content_encoding: str | None = None, content_language: str | None = None, content_disposition: str | None = None, cache_control: str | None = None, content_md5: bytearray | None = None, **kwargs: Any)[source]

Used to store the content settings of a file.

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

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

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

  • content_disposition (Optional[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 (Optional[str]) – If the cache_control has previously been set for the file, that value is stored.

  • content_md5 (Optional[bytearray]) – 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()
cache_control: str | None = None

The cache control specified for the file.

content_disposition: str | None = None

The content disposition specified for the file.

content_encoding: str | None = None

The content encoding specified for the file.

content_language: str | None = None

The content language specified for the file.

content_md5: bytearray | None = None

The content md5 specified for the file.

content_type: str | None = None

The content type specified for the file.

class azure.storage.fileshare.CorsRule(allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any)[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 (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 (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.

  • allowed_origins (str) – The origin domains that are permitted to make a request against the storage service via CORS. The origin domain is the domain from which the request originates. Note that the origin must be an exact case-sensitive match with the origin that the user age sends to the service. You can also use the wildcard character ‘*’ to allow all origin domains to make requests via CORS. Required.

  • allowed_methods (str) – The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma separated). Required.

  • allowed_headers – The request headers that the origin domain may specify on the CORS request. Required.

  • exposed_headers – The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer. Required.

  • max_age_in_seconds – The maximum amount time that a browser should cache the preflight OPTIONS request. Required.

classmethod deserialize(data: Any, content_type: str | None = None) Self

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

Return type:

Self

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) Self

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

  • key_extractors (function) – A key extractor function.

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

Returns:

An instance of this model

Raises:

DeserializationError – if something went wrong

Return type:

Self

classmethod is_xml_model() bool
as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

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

Advanced usage might optionally 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

If you want XML serialization, you can pass the kwargs is_xml=True.

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

  • key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

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

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

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

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

Returns:

A dict JSON compatible object

Return type:

dict

allowed_headers: str

The comma-delimited string representation of the list of headers allowed to be a part of the cross-origin request.

allowed_methods: str

The comma-delimited string representation of the list of HTTP methods that are allowed to be executed by the origin.

allowed_origins: str

The comma-delimited string representation of the list of origin domains that will be allowed via CORS, or “*” to allow all domains.

exposed_headers: str

The comma-delimited string representation of the list of response headers to expose to CORS clients.

max_age_in_seconds: int

The number of seconds that the client/browser should cache a pre-flight response.

class azure.storage.fileshare.DirectoryProperties(**kwargs: Any)[source]

Directory’s properties class.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
change_time: datetime | str | None = None

Change time for the file.

creation_time: datetime | str | None = None

Creation time for the file.

etag: str

The ETag contains a value that you can use to perform operations conditionally.

file_attributes: str | NTFSAttributes

The file system attributes for files and directories.

file_id: str

FileId uniquely identifies the file or directory.

file_mode: str | None = None

NFS only. The file mode of the directory.

group: str | None = None

NFS only. The owning group of the directory.

is_directory: bool = True

Whether input is a directory.

last_access_time: datetime | None = None

Last access time for the file.

last_modified: datetime

A datetime object representing the last time the directory was modified.

last_write_time: datetime | str | None = None

Last write time for the file.

metadata: Dict[str, str]

Name_value pairs to associate with the directory as metadata.

name: str

The name of the directory.

nfs_file_type: Literal['Directory'] | None = None

NFS only. The type of the directory.

owner: str | None = None

NFS only. The owner of the directory.

parent_id: str

ParentId uniquely identifies the parent directory of the object.

permission_key: str

Key of the permission to be set for the directory/file.

server_encrypted: bool

Whether encryption is enabled.

class azure.storage.fileshare.ExponentialRetry(initial_backoff: int = 15, increment_base: int = 3, retry_total: int = 3, retry_to_secondary: bool = False, random_jitter_range: int = 3, **kwargs: Any)[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.

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.

  • retry_total (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: PipelineRequest) Dict[str, Any]
get_backoff_time(settings: Dict[str, Any]) float[source]

Calculates how long to sleep before retrying.

Parameters:

settings (Dict[str, Any]]) – The configurable values pertaining to get backoff time.

Returns:

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

Return type:

float

increment(settings: Dict[str, Any], request: PipelineRequest, response: PipelineResponse | None = None, error: AzureError | None = None) bool

Increment the retry counters.

Parameters:
  • settings (Dict[str, Any]) – The configurable values pertaining to the increment operation.

  • request (PipelineRequest) – A pipeline request object.

  • response (Optional[PipelineResponse]) – A pipeline response object.

  • error (Optional[AzureError]) – An error encountered during the request, or None if the response was received successfully.

Returns:

Whether the retry attempts are exhausted.

Return type:

bool

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)
connect_retries: int

The max number of connect retries.

increment_base: int

The base, in seconds, to increment the initial_backoff by after the first retry.

initial_backoff: int

The initial backoff interval, in seconds, for the first retry.

next: HTTPPolicy[HTTPRequestType, HTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

random_jitter_range: int

A number in seconds which indicates a range to jitter/randomize for the back-off interval.

retry_read: int

The max number of read retries.

retry_status: int

The max number of status retries.

retry_to_secondary: bool

Whether the secondary endpoint should be retried.

total_retries: int

The max number of retries.

class azure.storage.fileshare.FileProperties(**kwargs: Any)[source]

File’s properties class.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
change_time: datetime | str | None = None

Change time for the file.

content_length: int

Size of file in bytes.

content_range: str | None = None

Indicates the range of bytes returned in the event that the client requested a subset of the file.

content_settings: ContentSettings

The content settings for the file.

copy: CopyProperties

The copy properties.

creation_time: datetime | str | None = None

Creation time for the file.

etag: str

The ETag contains a value that can be used to perform operations conditionally.

file_attributes: str | NTFSAttributes

The file system attributes for files and directories.

file_id: str

FileId uniquely identifies the file or directory.

file_mode: str | None = None

NFS only. The file mode of the file.

file_type: str

String indicating the type of file.

group: str | None = None

NFS only. The owning group of the file.

is_directory: bool = False

Whether input is a directory.

last_access_time: datetime | None = None

Last access time for the file.

last_modified: datetime

A datetime object representing the last time the file was modified.

last_write_time: datetime | str | None = None

Last write time for the file.

lease: LeaseProperties

File lease properties.

NFS only. The number of hard links of the file.

metadata: Dict[str, str]

Name-value pairs to associate with the file as metadata.

name: str

The name of the file.

nfs_file_type: Literal['Regular'] | None = None

NFS only. The type of the file.

owner: str | None = None

NFS only. The owner of the file.

parent_id: str | None = None

ParentId uniquely identifies the parent directory of the object.

path: str | None = None

The path of the file.

permission_key: str

Key of the permission to be set for the directory/file.

server_encrypted: bool

Whether encryption is enabled.

share: str | None = None

The name of the share.

size: int

Size of the file in bytes.

snapshot: str | None = None

File snapshot.

class azure.storage.fileshare.FileSasPermissions(read: bool = False, create: bool = False, write: bool = False, delete: bool = 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: str) Self[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

create: bool = False

Create a new file or copy a file to a new file.

delete: bool = False

Delete the file.

read: bool = False

Read the content, properties, metadata. Use the file as the source of a copy operation.

write: bool = False

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

class azure.storage.fileshare.Handle(**kwargs: Any)[source]

A listed Azure Storage handle item.

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

Keyword Arguments:
  • client_name (str) – Name of the client machine where the share is being mounted.

  • handle_id (str) – XSMB service handle ID.

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

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

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

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

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

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

  • last_reconnect_time (Optional[datetime]) – Time handle was last connected to. (UTC)

  • access_rights (List[Literal['Read', 'Write', 'Delete']]) – Access rights of the handle.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
access_rights: List[Literal['Read', 'Write', 'Delete']]

Access rights of the handle.

client_ip: str

Client IP that opened the handle.

client_name: str

Name of the client machine where the share is being mounted.

file_id: str

FileId uniquely identifies the file or directory.

id: str

XSMB service handle ID.

last_reconnect_time: datetime | None

Time handle that was last connected to. (UTC)

open_time: datetime

Time when the session that previously opened the handle was last been reconnected. (UTC)

parent_id: str

ParentId uniquely identifies the parent directory of the object.

path: str

File or directory name including full path starting from share root.

session_id: str

SMB session ID in context of which the file handle was opened.

class azure.storage.fileshare.LinearRetry(backoff: int = 15, retry_total: int = 3, retry_to_secondary: bool = False, random_jitter_range: int = 3, **kwargs: Any)[source]

Linear retry.

Constructs a Linear retry object.

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

  • retry_total (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: PipelineRequest) Dict[str, Any]
get_backoff_time(settings: Dict[str, Any]) float[source]

Calculates how long to sleep before retrying.

Parameters:

settings (Dict[str, Any]]) – The configurable values pertaining to the backoff time.

Returns:

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

Return type:

float

increment(settings: Dict[str, Any], request: PipelineRequest, response: PipelineResponse | None = None, error: AzureError | None = None) bool

Increment the retry counters.

Parameters:
  • settings (Dict[str, Any]) – The configurable values pertaining to the increment operation.

  • request (PipelineRequest) – A pipeline request object.

  • response (Optional[PipelineResponse]) – A pipeline response object.

  • error (Optional[AzureError]) – An error encountered during the request, or None if the response was received successfully.

Returns:

Whether the retry attempts are exhausted.

Return type:

bool

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)
connect_retries: int

The max number of connect retries.

initial_backoff: int

The backoff interval, in seconds, between retries.

next: HTTPPolicy[HTTPRequestType, HTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

random_jitter_range: int

A number in seconds which indicates a range to jitter/randomize for the back-off interval.

retry_read: int

The max number of read retries.

retry_status: int

The max number of status retries.

retry_to_secondary: bool

Whether the secondary endpoint should be retried.

total_retries: int

The max number of retries.

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.Metrics(**kwargs: Any)[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. The default value is 1.0.

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

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

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

  • version – The version of Storage Analytics to configure. Required.

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

  • include_apis – Indicates whether metrics should generate summary statistics for called API operations.

  • retention_policy – The retention policy.

classmethod deserialize(data: Any, content_type: str | None = None) Self

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

Return type:

Self

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) Self

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

  • key_extractors (function) – A key extractor function.

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

Returns:

An instance of this model

Raises:

DeserializationError – if something went wrong

Return type:

Self

classmethod is_xml_model() bool
as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

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

Advanced usage might optionally 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

If you want XML serialization, you can pass the kwargs is_xml=True.

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

  • key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

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

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

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

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

Returns:

A dict JSON compatible object

Return type:

dict

enabled: bool = False

Indicates whether metrics are enabled for the File service.

include_apis: bool

Indicates whether metrics should generate summary statistics for called API operations.

retention_policy: RetentionPolicy = <azure.storage.fileshare._models.RetentionPolicy object>

Determines how long the associated data should persist.

version: str = '1.0'

The version of Storage Analytics to configure.

class azure.storage.fileshare.NTFSAttributes(read_only: bool = False, hidden: bool = False, system: bool = False, none: bool = False, directory: bool = False, archive: bool = False, temporary: bool = False, offline: bool = False, not_content_indexed: bool = False, no_scrub_data: bool = 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.

classmethod from_string(string: str) Self[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

archive: bool = False

Enable/disable ‘Archive’ attribute for DIRECTORY.

directory: bool = False

Enable/disable ‘Directory’ attribute for DIRECTORY.

hidden: bool = False

Enable/disable ‘Hidden’ attribute for DIRECTORY or FILE.

no_scrub_data: bool = False

Enable/disable ‘NoScrubData’ attribute for DIRECTORY.

none: bool = False

Enable/disable ‘None’ attribute for DIRECTORY or FILE to clear all attributes of FILE/DIRECTORY.

not_content_indexed: bool = False

Enable/disable ‘NotContentIndexed’ attribute for DIRECTORY.

offline: bool = False

Enable/disable ‘Offline’ attribute for DIRECTORY.

read_only: bool = False

Enable/disable ‘ReadOnly’ attribute for DIRECTORY or FILE.

system: bool = False

Enable/disable ‘System’ attribute for DIRECTORY or FILE.

temporary: bool = False

Enable/disable ‘Temporary’ attribute for DIRECTORY.

class azure.storage.fileshare.ResourceTypes(service: bool = False, container: bool = False, object: bool = 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

container: bool = False
object: bool = False
service: bool = False
class azure.storage.fileshare.RetentionPolicy(enabled: bool = False, days: int | None = 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) – Indicates whether a retention policy is enabled for the storage service.

  • days (Optional[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.

Keyword Arguments:
  • enabled (bool) – Indicates whether a retention policy is enabled for the File service. If false, metrics data is retained, and the user is responsible for deleting it. Required.

  • days (int) – Indicates the number of days that metrics data should be retained. All data older than this value will be deleted. Metrics data is deleted on a best-effort basis after the retention period expires.

classmethod deserialize(data: Any, content_type: str | None = None) Self

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

Return type:

Self

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) Self

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

  • key_extractors (function) – A key extractor function.

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

Returns:

An instance of this model

Raises:

DeserializationError – if something went wrong

Return type:

Self

classmethod is_xml_model() bool
as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

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

Advanced usage might optionally 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

If you want XML serialization, you can pass the kwargs is_xml=True.

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

  • key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

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

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

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

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

Returns:

A dict JSON compatible object

Return type:

dict

days: int | None = None

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.

enabled: bool = False

Indicates whether a retention policy is enabled for the storage service.

class azure.storage.fileshare.Services(*, blob: bool = False, queue: bool = False, fileshare: bool = False)[source]

Specifies the services accessible with the account SAS.

Keyword Arguments:
  • blob (bool) – Access for the ~azure.storage.blob.BlobServiceClient. Default is False.

  • queue (bool) – Access for the ~azure.storage.queue.QueueServiceClient. Default is False.

  • fileshare (bool) – Access for the ~azure.storage.fileshare.ShareServiceClient. Default is False.

classmethod from_string(string)[source]

Create Services from a string.

To specify blob, queue, or file you need only to include the first letter of the word in the string. E.g. for blob and queue you would provide a string “bq”.

Parameters:

string (str) – Specify blob, queue, or file in in the string with the first letter of the word.

Returns:

A Services object

Return type:

Services

class azure.storage.fileshare.ShareAccessTier(*values)[source]

ShareAccessTier.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count()

Return the number of non-overlapping occurrences of substring sub in string S[start:end].

Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith()

Return True if the string ends with the specified suffix, False otherwise.

suffix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

format(*args, **kwargs)

Return a formatted version of the string, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping, /)

Return a formatted version of the string, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if all characters in the string are printable, False otherwise.

A character is printable if repr() may use it in its output.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, /, count=-1)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

rindex()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith()

Return True if the string starts with the specified prefix, False otherwise.

prefix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

COOL = 'Cool'
HOT = 'Hot'
PREMIUM = 'Premium'
TRANSACTION_OPTIMIZED = 'TransactionOptimized'
class azure.storage.fileshare.ShareClient(account_url: str, share_name: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, *, token_intent: Literal['backup'] | None = None, **kwargs: Any)[source]

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

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

For more optional configuration, please click here.

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

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

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

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

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

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

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

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

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

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

  • api_version (str) –

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

    Added in version 12.1.0.

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

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

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

Create ShareClient from a Connection String.

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

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

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

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

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: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any) Self[source]
Parameters:
  • share_url (str) – The full URI to the share.

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

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

Returns:

A share client.

Return type:

ShareClient

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

Requests a new lease.

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

Added in version 12.5.0.

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

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

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

Returns:

A ShareLeaseClient object.

Return type:

ShareLeaseClient

Example:

Acquiring a lease on a share.
share.create_directory("mydir")
lease = share.acquire_lease()
share.get_share_properties(lease=lease)
share.delete_share(lease=lease)
close()

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

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

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

Parameters:

directory_name (str) – The name of the directory.

Keyword Arguments:
Returns:

ShareDirectoryClient

Return type:

ShareDirectoryClient

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

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

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

Parameters:

file_permission (str) – File permission, a Portable SDDL

Keyword Arguments:
Returns:

A file permission key

Return type:

str or None

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

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

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

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

dict[str, Any]

Example:

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

Creates a snapshot of the share.

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

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

Keyword Arguments:
Returns:

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

Return type:

dict[str, Any]

Example:

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

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

Parameters:

directory_name (str) – The name of the directory.

Keyword Arguments:

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

Return type:

None

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

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

Parameters:

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

Keyword Arguments:
  • lease

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

    Added in version 12.5.0.

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

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

Example:

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

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

Parameters:

directory_path (str) – Path to the specified directory.

Returns:

A Directory Client.

Return type:

ShareDirectoryClient

get_file_client(file_path: str) ShareFileClient[source]

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

Parameters:

file_path (str) – Path to the specified file.

Returns:

A File Client.

Return type:

ShareFileClient

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

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

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

Parameters:

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

Keyword Arguments:
Returns:

A file permission (a portable SDDL)

Return type:

str

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

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

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

  • lease

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

    Added in version 12.5.0.

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

Returns:

Access policy information in a dict.

Return type:

dict[str, Any]

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

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

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

  • lease

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

    Added in version 12.5.0.

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

Returns:

The share properties.

Return type:

ShareProperties

Example:

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

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

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

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

  • lease

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

    Added in version 12.5.0.

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

Returns:

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

Return type:

int

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

Lists the directories and files under the share.

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

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

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

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

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

    Added in version 12.6.0.

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

  • include_extended_info (bool) –

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

    Added in version 12.6.0.

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

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

Returns:

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

Return type:

ItemPaged[Union[DirectoryProperties, FileProperties]]

Example:

List directories and files in the share.
# Create a directory in the share
dir_client = 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: Dict[str, AccessPolicy], **kwargs: Any) Dict[str, Any][source]

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

Parameters:

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

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

  • lease

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

    Added in version 12.5.0.

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

Returns:

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

Return type:

dict[str, Any]

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

Sets the metadata for the share.

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

Parameters:

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

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

  • lease

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

    Added in version 12.5.0.

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

Returns:

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

Return type:

dict[str, Any]

Example:

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

Sets the share properties.

Added in version 12.4.0.

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

dict[str, Any]

Example:

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

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

Sets the quota for the share.

Parameters:

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

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

  • lease

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

    Added in version 12.5.0.

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

Returns:

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

Return type:

dict[str, Any]

Example:

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

The version of the Storage API used for requests.

Return type:

str

property location_mode

The location mode that the client is currently using.

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

Return type:

str

property primary_endpoint

The full primary endpoint URL.

Return type:

str

property primary_hostname

The hostname of the primary endpoint.

Return type:

str

property secondary_endpoint

The full secondary endpoint URL if configured.

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

Return type:

str

Raises:

ValueError

property secondary_hostname

The hostname of the secondary endpoint.

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

Return type:

Optional[str]

property url

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

This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode().

Returns:

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

Return type:

str

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

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

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

For more optional configuration, please click here.

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

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

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

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

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

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

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

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

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

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

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

  • api_version (str) –

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

    Added in version 12.1.0.

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

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

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

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

Create ShareDirectoryClient from a Connection String.

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

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

  • directory_path (str) – The directory path.

  • credential (Optional[Union[str, dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]]) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

Keyword Arguments:

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

Returns:

A directory client.

Return type:

ShareDirectoryClient

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

Create a ShareDirectoryClient from a directory url.

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

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

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

Keyword Arguments:

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

Returns:

A directory client.

Return type:

ShareDirectoryClient

close()

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

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

Close any open file handles.

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

Parameters:

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

Keyword Arguments:

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

Returns:

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

Return type:

dict[str, int]

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

Close an open file handle.

Parameters:

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

Keyword Arguments:

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

Returns:

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

Return type:

dict[str, int]

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

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

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

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

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

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

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

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

  • file_change_time (str or datetime) –

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

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

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

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

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

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

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

Returns:

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

Return type:

dict[str, Any]

Example:

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

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

Parameters:

directory_name (str) – The name of the subdirectory.

Keyword Arguments:
Returns:

ShareDirectoryClient

Return type:

ShareDirectoryClient

Example:

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

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

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

Keyword Arguments:

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

Return type:

None

Example:

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

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

Parameters:

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

Keyword Arguments:

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

Return type:

None

Example:

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

Deletes a subdirectory.

Parameters:

directory_name (str) – The name of the subdirectory.

Keyword Arguments:

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

Return type:

None

Example:

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

Returns True if a directory exists and returns False otherwise.

Keyword Arguments:

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

Returns:

True if the directory exists, False otherwise.

Return type:

bool

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

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

Keyword Arguments:

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

Returns:

DirectoryProperties

Return type:

DirectoryProperties

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

Get a client to interact with a specific file.

The file need not already exist.

Parameters:

file_name (str) – The name of the file.

Returns:

A File Client.

Return type:

ShareFileClient

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

Get a client to interact with a specific subdirectory.

The subdirectory need not already exist.

Parameters:

directory_name (str) – The name of the subdirectory.

Returns:

A Directory Client.

Return type:

ShareDirectoryClient

Example:

Gets the subdirectory client.
# Get a directory client and create the directory
parent = share.get_directory_client("dir1")
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: str | None = None, **kwargs: Any) ItemPaged[DirectoryProperties | FileProperties][source]

Lists all the directories and files under the directory.

Parameters:

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

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

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

    Added in version 12.6.0.

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

  • include_extended_info (bool) –

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

    Added in version 12.6.0.

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

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

Returns:

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

Return type:

ItemPaged[Union[DirectoryProperties, FileProperties]]

Example:

List directories and files.
# List the directories and files under the parent directory
my_list = list(parent_dir.list_directories_and_files())
print(my_list)
list_handles(recursive: bool = False, **kwargs: Any) ItemPaged[Handle][source]

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

Parameters:

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

Keyword Arguments:

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

Returns:

An auto-paging iterable of Handle

Return type:

ItemPaged[Handle]

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

Rename the source directory.

Parameters:

new_name (str) – The new directory name.

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

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

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

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

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

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

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

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

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

  • file_change_time (str or datetime) –

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

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

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

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

Returns:

The new Directory Client.

Return type:

ShareDirectoryClient

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

Sets the metadata for the directory.

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

Parameters:

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

Keyword Arguments:

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

Returns:

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

Return type:

dict[str, Any]

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

Sets HTTP headers on the directory.

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

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

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

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

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

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

  • file_change_time (str or datetime) –

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

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

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

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

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

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

Returns:

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

Return type:

dict[str, Any]

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

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

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

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

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

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

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

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

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

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

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

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

Returns:

ShareFileClient

Return type:

ShareFileClient

Example:

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

The version of the Storage API used for requests.

Return type:

str

property location_mode

The location mode that the client is currently using.

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

Return type:

str

property primary_endpoint

The full primary endpoint URL.

Return type:

str

property primary_hostname

The hostname of the primary endpoint.

Return type:

str

property secondary_endpoint

The full secondary endpoint URL if configured.

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

Return type:

str

Raises:

ValueError

property secondary_hostname

The hostname of the secondary endpoint.

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

Return type:

Optional[str]

property url

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

This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode().

Returns:

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

Return type:

str

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

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

For more optional configuration, please click here.

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

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

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

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

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

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

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

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

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

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

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

  • api_version (str) –

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

    Added in version 12.1.0.

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

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

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

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

Create ShareFileClient from a Connection String.

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

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

  • file_path (str) – The file path.

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

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

Keyword Arguments:

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

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: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any) Self[source]

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

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

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

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

Keyword Arguments:

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

Returns:

A File client.

Return type:

ShareFileClient

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

Abort an ongoing copy operation.

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

Parameters:

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

Keyword Arguments:
Return type:

None

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

Requests a new lease.

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

Parameters:

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

Keyword Arguments:

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

Returns:

A ShareLeaseClient object.

Return type:

ShareLeaseClient

Example:

Acquiring a lease on a file.
source_file.create_file(1024)
lease = source_file.acquire_lease()
source_file.upload_file(b'hello world', lease=lease)

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

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

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

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

Keyword Arguments:
Returns:

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

Return type:

Dict[str, Any]

close()

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

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

Close any open file handles.

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

Keyword Arguments:

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

Returns:

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

Return type:

dict[str, int]

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

Close an open file handle.

Parameters:

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

Keyword Arguments:

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

Returns:

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

Return type:

dict[str, int]

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

Creates a new file.

Note that it only initializes the file with no content.

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

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

  • file_creation_time (str or datetime or None) – Creation time for the file Default value: Now.

  • file_last_write_time (str or datetime or None) – 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:
  • file_permission_format (Literal['sddl', 'binary']) – Specifies the format in which the permission is returned. If not specified, SDDL will be the default.

  • file_change_time (str or datetime) –

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

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

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

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

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

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

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

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

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

Returns:

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

Return type:

dict[str, Any]

Example:

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

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

Parameters:

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

Keyword Arguments:
Returns:

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

Return type:

dict[str, Any]

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

Parameters:

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

Keyword Arguments:
Returns:

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

Return type:

dict[str, Any]

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

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

Keyword Arguments:
Return type:

None

Example:

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

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

Parameters:
  • offset (int) – Start of byte range to use for downloading a section of the file. Must be set if length is provided.

  • length (int) – Number of bytes to read from the stream. This is optional, but should be supplied for optimal performance.

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

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

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

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

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

Returns:

A streaming object (StorageStreamDownloader)

Return type:

StorageStreamDownloader

Example:

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

Returns True if the file exists and returns False otherwise.

Keyword Arguments:

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

Returns:

True if the file exists, False otherwise.

Return type:

bool

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

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

Keyword Arguments:
Returns:

FileProperties

Return type:

FileProperties

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

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

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

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

Keyword Arguments:
Returns:

A list of valid ranges.

Return type:

List[dict[str, int]]

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

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

Added in version 12.6.0.

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

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

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

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

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

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

Returns:

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

Return type:

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

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

Keyword Arguments:

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

Returns:

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

Return type:

dict[str, Any]

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

Lists handles for file.

Keyword Arguments:

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

Returns:

An auto-paging iterable of Handle

Return type:

ItemPaged[Handle]

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

Rename the source file.

Parameters:

new_name (str) – The new file name.

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

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

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

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

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

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

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

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

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

  • file_change_time (str or datetime) –

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

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

  • content_type (str) –

    The Content Type of the new file.

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

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

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

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

Returns:

The new File Client.

Return type:

ShareFileClient

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

Resizes a file to the specified size.

Parameters:

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

Keyword Arguments:
Returns:

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

Return type:

Dict[str, Any]

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

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

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

Parameters:

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

Keyword Arguments:
Returns:

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

Return type:

dict[str, Any]

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

Sets HTTP headers on the file.

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

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

  • file_creation_time (str or datetime or None) – Creation time for the file Default value: Preserve.

  • file_last_write_time (str or datetime or None) – 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:
  • file_permission_format (Literal['sddl', 'binary']) – Specifies the format in which the permission is returned. If not specified, SDDL will be the default.

  • file_change_time (str or datetime) –

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

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

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

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

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

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

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

Returns:

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

Return type:

dict[str, Any]

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

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

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

Parameters:

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

Keyword Arguments:
  • file_permission (str) –

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

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

  • permission_key (str) –

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

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

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

  • file_attributes (str or NTFSAttributes) –

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

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

  • file_creation_time (str or datetime) –

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

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

  • file_last_write_time (str or datetime) –

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

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

  • file_change_time (str or datetime) –

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

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

  • ignore_read_only (bool) –

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

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

  • set_archive_attribute (bool) –

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

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

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

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

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

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

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

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

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

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

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

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

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

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

Returns:

Response after data copying operation has been initiated.

Return type:

dict[str, Any]

Example:

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

Uploads a new file.

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

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

  • file_attributes (str or NTFSAttributes) – 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:
  • file_change_time (str or datetime) –

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

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

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

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

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

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

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

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

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

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

Returns:

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: bytes, offset: int, length: int, **kwargs: Any) Dict[str, Any][source]

Upload a range of bytes to a file.

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

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

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

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

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

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

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

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

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

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

Returns:

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

Return type:

Dict[str, Any]

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

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

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

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

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

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

Keyword Arguments:
  • source_if_modified_since (datetime) – A DateTime value. Azure expects the date value passed in to be UTC. If timezone is included, any non-UTC datetimes will be converted to UTC. If a date is passed in without timezone info, it is assumed to be UTC. Specify this conditional header to copy the blob only if the source blob has been modified since the specified date/time.

  • source_if_unmodified_since (datetime) – A DateTime value. Azure expects the date value passed in to be UTC. If timezone is included, any non-UTC datetimes will be converted to UTC. If a date is passed in without timezone info, it is assumed to be UTC. Specify this conditional header to copy the blob only if the source blob has not been modified since the specified date/time.

  • source_etag (str) – The source ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

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

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

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

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

  • lease (ShareLeaseClient or str) –

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

    Added in version 12.1.0.

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

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

Returns:

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

Return type:

dict[str, Any]

property api_version

The version of the Storage API used for requests.

Return type:

str

property location_mode

The location mode that the client is currently using.

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

Return type:

str

property primary_endpoint

The full primary endpoint URL.

Return type:

str

property primary_hostname

The hostname of the primary endpoint.

Return type:

str

property secondary_endpoint

The full secondary endpoint URL if configured.

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

Return type:

str

Raises:

ValueError

property secondary_hostname

The hostname of the secondary endpoint.

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

Return type:

Optional[str]

property url

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

This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode().

Returns:

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

Return type:

str

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

Creates a new ShareLeaseClient.

This client provides lease operations on a ShareClient or ShareFileClient.

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

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

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

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

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

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

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

Return type:

None

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

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

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

Keyword Arguments:
  • lease_break_period (int) –

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

    Added in version 12.6.0.

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

Returns:

Approximate time remaining in the lease period, in seconds.

Return type:

int

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

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

Parameters:

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

Keyword Arguments:

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

Returns:

None

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

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

Keyword Arguments:

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

Returns:

None

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

Renews the share lease.

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

Added in version 12.6.0.

Keyword Arguments:

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

Returns:

None

etag: str | None

The ETag of the lease currently being maintained. This will be None if no lease has yet been acquired or modified.

id: str

The ID of the lease currently being maintained. This will be None if no lease has yet been acquired.

last_modified: datetime | None

The last modified timestamp of the lease currently being maintained. This will be None if no lease has yet been acquired or modified.

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

Share’s properties class.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
access_tier: str

The share’s access tier.’

deleted: bool | None = None

Whether this share was deleted. This is a service returned value, and the value will be set when list shared including deleted ones.

deleted_time: datetime | None = None

A datetime object representing the time at which the share was deleted. This is a service returned value, and the value will be set when list shared including deleted ones.

enable_snapshot_virtual_directory_access: bool | None = None

Specifies whether the snapshot virtual directory should be accessible at the root of the share mount point when NFS is enabled. if not specified, the default is True.

etag: str

The ETag contains a value that you can use to perform operations conditionally.

last_modified: datetime

A datetime object representing the last time the share was modified.

lease: LeaseProperties

Share lease properties.

metadata: Dict[str, str]

Name-value pairs associate with the share as metadata.

name: str

The name of the share.

next_allowed_quota_downgrade_time: str | None = None

The share’s next allowed quota downgrade time.

next_provisioned_bandwidth_downgrade: datetime | None

The share’s next allowed provisioned bandwidth downgrade time.

next_provisioned_iops_downgrade: datetime | None

The share’s next allowed provisioned throughput downgrade time.

paid_bursting_bandwidth_mibps: int | None = None

The maximum throughput the file share can support in MiB/s.

paid_bursting_enabled: int | None = None

This property enables paid bursting.

paid_bursting_iops: int | None = None

The maximum IOPS the file share can support.

protocols: List[str] | None = None

Indicates the protocols enabled on the share. The protocol can be either SMB or NFS.

provisioned_bandwidth: int | None = None

Provisioned bandwidth in megabits/second. Only applicable to premium file accounts.

provisioned_egress_mbps: int | None = None

Provisioned egress in megabits/second. Only applicable to premium file accounts.

provisioned_ingress_mbps: int | None = None

Provisioned ingress in megabits/second. Only applicable to premium file accounts.

provisioned_iops: int | None = None

Provisioned input/output operators per second (iops). Only applicable to premium file accounts.

quota: int

The allocated quota.

remaining_retention_days: int | None = None

The number of days that the share will be retained before being permanently deleted by the service. This is a service returned value, and the value will be set when list shared including deleted ones.

root_squash: ShareRootSquash | str | None = None

‘NoRootSquash’, ‘RootSquash’, ‘AllSquash’.

Type:

Possible values include

snapshot: str | None = None

Snapshot of the share.

version: str | None = None

To indicate the version of deleted share. This is a service returned value, and the value will be set when list shared including deleted ones.

class azure.storage.fileshare.ShareProtocolSettings(**kwargs: Any)[source]

Protocol Settings class used by the set and get service properties methods in the share service.

Contains protocol properties of the share service such as the SMB setting of the share service.

Keyword Arguments:
  • smb (ShareSmbSettings) – Sets SMB settings.

  • smb – Settings for SMB protocol.

classmethod deserialize(data: Any, content_type: str | None = None) Self

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

Return type:

Self

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) Self

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

  • key_extractors (function) – A key extractor function.

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

Returns:

An instance of this model

Raises:

DeserializationError – if something went wrong

Return type:

Self

classmethod is_xml_model() bool
as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

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

Advanced usage might optionally 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

If you want XML serialization, you can pass the kwargs is_xml=True.

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

  • key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

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

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

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

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

Returns:

A dict JSON compatible object

Return type:

dict

smb: ShareSmbSettings

Sets the SMB settings.

class azure.storage.fileshare.ShareProtocols(*values)[source]

Enabled protocols on the share

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count()

Return the number of non-overlapping occurrences of substring sub in string S[start:end].

Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith()

Return True if the string ends with the specified suffix, False otherwise.

suffix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

format(*args, **kwargs)

Return a formatted version of the string, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping, /)

Return a formatted version of the string, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if all characters in the string are printable, False otherwise.

A character is printable if repr() may use it in its output.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, /, count=-1)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

rindex()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith()

Return True if the string starts with the specified prefix, False otherwise.

prefix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

NFS = 'NFS'
SMB = 'SMB'
class azure.storage.fileshare.ShareRootSquash(*values)[source]

ShareRootSquash.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count()

Return the number of non-overlapping occurrences of substring sub in string S[start:end].

Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith()

Return True if the string ends with the specified suffix, False otherwise.

suffix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

format(*args, **kwargs)

Return a formatted version of the string, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping, /)

Return a formatted version of the string, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if all characters in the string are printable, False otherwise.

A character is printable if repr() may use it in its output.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, /, count=-1)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

rindex()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith()

Return True if the string starts with the specified prefix, False otherwise.

prefix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

ALL_SQUASH = 'AllSquash'
NO_ROOT_SQUASH = 'NoRootSquash'
ROOT_SQUASH = 'RootSquash'
class azure.storage.fileshare.ShareSasPermissions(read: bool = False, write: bool = False, delete: bool = False, list: bool = False, create: bool = 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.

  • create (bool) – Create a new file in the share, or copy a file to a new file in the share.

classmethod from_string(permission: str) Self[source]

Create a ShareSasPermissions from a string.

To specify read, create, 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, create, write, delete, or list permissions

Returns:

A ShareSasPermissions object

Return type:

ShareSasPermissions

create: bool = False

The create permission for share SAS.

delete: bool = False

The delete permission for share SAS.

list: bool = False

The list permission for share SAS.

read: bool = False

The read permission for share SAS.

write: bool = False

The write permission for share SAS.

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

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

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

For more optional configuration, please click here.

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

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

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

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

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

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

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

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

  • api_version (str) –

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

    Added in version 12.1.0.

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

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

Example:

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

Create ShareServiceClient from a Connection String.

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

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

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

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

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

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

Parameters:

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

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

  • quota (int) – Quota in bytes.

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

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

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

Returns:

A ShareClient for the newly created Share.

Return type:

ShareClient

Example:

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

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

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

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

Keyword Arguments:

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

Return type:

None

Example:

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

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

Keyword Arguments:

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

Returns:

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

Return type:

Dict[str, Any]

Example:

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

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

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

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

Returns:

A ShareClient.

Return type:

ShareClient

Example:

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

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

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

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

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

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

Keyword Arguments:
Returns:

An iterable (auto-paging) of ShareProperties.

Return type:

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: Metrics | None = None, minute_metrics: Metrics | None = None, cors: List[CorsRule] | None = None, protocol: ShareProtocolSettings | None = None, **kwargs: Any) None[source]

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

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

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

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

  • protocol (ShareProtocolSettings) – Sets protocol settings

Keyword Arguments:

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

Return type:

None

Example:

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

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

# Create CORS rules
cors_rule1 = CorsRule(['www.xyz.com'], ['GET'])
allowed_origins = ['www.xyz.com', "www.ab.com", "www.bc.com"]
allowed_methods = ['GET', 'PUT']
max_age_in_seconds = 500
exposed_headers = ["x-ms-meta-data*", "x-ms-meta-source*", "x-ms-meta-abc", "x-ms-meta-bcd"]
allowed_headers = ["x-ms-meta-data*", "x-ms-meta-target*", "x-ms-meta-xyz", "x-ms-meta-foo"]
cors_rule2 = CorsRule(
    allowed_origins,
    allowed_methods,
    max_age_in_seconds=max_age_in_seconds,
    exposed_headers=exposed_headers,
    allowed_headers=allowed_headers)

cors = [cors_rule1, cors_rule2]

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

Restores soft-deleted share.

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

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

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

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

Keyword Arguments:

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

Returns:

A ShareClient for the undeleted Share.

Return type:

ShareClient

property api_version

The version of the Storage API used for requests.

Return type:

str

property location_mode

The location mode that the client is currently using.

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

Return type:

str

property primary_endpoint

The full primary endpoint URL.

Return type:

str

property primary_hostname

The hostname of the primary endpoint.

Return type:

str

property secondary_endpoint

The full secondary endpoint URL if configured.

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

Return type:

str

Raises:

ValueError

property secondary_hostname

The hostname of the secondary endpoint.

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

Return type:

Optional[str]

property url

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

This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode().

Returns:

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

Return type:

str

class azure.storage.fileshare.ShareSmbSettings(**kwargs: Any)[source]

Settings for the SMB protocol.

Keyword Arguments:
  • multichannel (SmbMultichannel) – Sets the multichannel settings.

  • multichannel – Settings for SMB Multichannel.

classmethod deserialize(data: Any, content_type: str | None = None) Self

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

Return type:

Self

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) Self

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

  • key_extractors (function) – A key extractor function.

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

Returns:

An instance of this model

Raises:

DeserializationError – if something went wrong

Return type:

Self

classmethod is_xml_model() bool
as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

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

Advanced usage might optionally 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

If you want XML serialization, you can pass the kwargs is_xml=True.

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

  • key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

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

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

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

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

Returns:

A dict JSON compatible object

Return type:

dict

multichannel: SmbMultichannel

Sets the multichannel settings.

class azure.storage.fileshare.SmbMultichannel(**kwargs: Any)[source]

Settings for Multichannel.

Keyword Arguments:
  • enabled (bool) – If SMB Multichannel is enabled.

  • enabled – If SMB multichannel is enabled.

classmethod deserialize(data: Any, content_type: str | None = None) Self

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

Return type:

Self

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) Self

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

  • key_extractors (function) – A key extractor function.

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

Returns:

An instance of this model

Raises:

DeserializationError – if something went wrong

Return type:

Self

classmethod is_xml_model() bool
as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

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

Advanced usage might optionally 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

If you want XML serialization, you can pass the kwargs is_xml=True.

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

  • key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

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

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

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

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

Returns:

A dict JSON compatible object

Return type:

dict

enabled: bool | None

If SMB Multichannel is enabled.

class azure.storage.fileshare.StorageErrorCode(*values)[source]
static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count()

Return the number of non-overlapping occurrences of substring sub in string S[start:end].

Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith()

Return True if the string ends with the specified suffix, False otherwise.

suffix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

format(*args, **kwargs)

Return a formatted version of the string, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping, /)

Return a formatted version of the string, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if all characters in the string are printable, False otherwise.

A character is printable if repr() may use it in its output.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, /, count=-1)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

rindex()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith()

Return True if the string starts with the specified prefix, False otherwise.

prefix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

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_ACCESS_TIER_NOT_SUPPORTED_FOR_ACCOUNT_TYPE = 'BlobAccessTierNotSupportedForAccountType'
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'
CONTENT_LENGTH_MUST_BE_ZERO = 'ContentLengthMustBeZero'
COPY_ACROSS_ACCOUNTS_NOT_SUPPORTED = 'CopyAcrossAccountsNotSupported'
COPY_ID_MISMATCH = 'CopyIdMismatch'
DELETE_PENDING = 'DeletePending'
DESTINATION_PATH_IS_BEING_DELETED = 'DestinationPathIsBeingDeleted'
DIRECTORY_NOT_EMPTY = 'DirectoryNotEmpty'
EMPTY_METADATA_KEY = 'EmptyMetadataKey'
FEATURE_VERSION_MISMATCH = 'FeatureVersionMismatch'
FILE_LOCK_CONFLICT = 'FileLockConflict'
FILE_SHARE_PROVISIONED_BANDWIDTH_DOWNGRADE_NOT_ALLOWED = 'FileShareProvisionedBandwidthDowngradeNotAllowed'
FILE_SHARE_PROVISIONED_IOPS_DOWNGRADE_NOT_ALLOWED = 'FileShareProvisionedIopsDowngradeNotAllowed'
FILE_SYSTEM_ALREADY_EXISTS = 'FilesystemAlreadyExists'
FILE_SYSTEM_BEING_DELETED = 'FilesystemBeingDeleted'
FILE_SYSTEM_NOT_FOUND = 'FilesystemNotFound'
INCREMENTAL_COPY_BLOB_MISMATCH = 'IncrementalCopyBlobMismatch'
INCREMENTAL_COPY_OF_EARLIER_VERSION_SNAPSHOT_NOT_ALLOWED = 'IncrementalCopyOfEarlierVersionSnapshotNotAllowed'
INCREMENTAL_COPY_OF_ERALIER_VERSION_SNAPSHOT_NOT_ALLOWED = 'IncrementalCopyOfEarlierVersionSnapshotNotAllowed'

Please use INCREMENTAL_COPY_OF_EARLIER_VERSION_SNAPSHOT_NOT_ALLOWED instead.

Type:

Deprecated

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_DESTINATION_PATH = 'InvalidDestinationPath'
INVALID_FILE_OR_DIRECTORY_PATH_NAME = 'InvalidFileOrDirectoryPathName'
INVALID_FLUSH_POSITION = 'InvalidFlushPosition'
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_PROPERTY_NAME = 'InvalidPropertyName'
INVALID_QUERY_PARAMETER_VALUE = 'InvalidQueryParameterValue'
INVALID_RANGE = 'InvalidRange'
INVALID_RENAME_SOURCE_PATH = 'InvalidRenameSourcePath'
INVALID_RESOURCE_NAME = 'InvalidResourceName'
INVALID_SOURCE_BLOB_TYPE = 'InvalidSourceBlobType'
INVALID_SOURCE_BLOB_URL = 'InvalidSourceBlobUrl'
INVALID_SOURCE_OR_DESTINATION_RESOURCE_TYPE = 'InvalidSourceOrDestinationResourceType'
INVALID_SOURCE_URI = 'InvalidSourceUri'
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_ALREADY_BROKEN = 'LeaseIsAlreadyBroken'
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_NAME_MISMATCH = 'LeaseNameMismatch'
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_AUTHENTICATION_INFORMATION = 'NoAuthenticationInformation'
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'
PATH_ALREADY_EXISTS = 'PathAlreadyExists'
PATH_CONFLICT = 'PathConflict'
PATH_NOT_FOUND = 'PathNotFound'
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'
RENAME_DESTINATION_PARENT_PATH_NOT_FOUND = 'RenameDestinationParentPathNotFound'
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 = 'SnapshotOperationRateExceeded'

Please use SNAPSHOT_OPERATION_RATE_EXCEEDED instead.

Type:

Deprecated

SNAPSHOTS_PRESENT = 'SnapshotsPresent'
SNAPSHOT_COUNT_EXCEEDED = 'SnapshotCountExceeded'
SNAPSHOT_OPERATION_RATE_EXCEEDED = 'SnapshotOperationRateExceeded'
SOURCE_CONDITION_NOT_MET = 'SourceConditionNotMet'
SOURCE_PATH_IS_BEING_DELETED = 'SourcePathIsBeingDeleted'
SOURCE_PATH_NOT_FOUND = 'SourcePathNotFound'
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_REST_VERSION = 'UnsupportedRestVersion'
UNSUPPORTED_XML_NODE = 'UnsupportedXmlNode'
azure.storage.fileshare.generate_account_sas(account_name: str, account_key: str, resource_types: ResourceTypes | str, permission: AccountSasPermissions | str, expiry: datetime | str, start: datetime | str | None = None, ip: str | None = None, *, services: ~azure.storage.fileshare._shared.models.Services | str = <azure.storage.fileshare._shared.models.Services object>, sts_hook: ~typing.Callable[[str], None] | None = None, **kwargs: ~typing.Any) str[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 or str) – Specifies the resource types that are accessible with the account SAS.

  • permission (AccountSasPermissions or str) – The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions.

  • expiry (datetime or str) – The time at which the shared access signature becomes invalid. The provided datetime will always be interpreted as UTC.

  • start (datetime or str or None) – 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. The provided datetime will always be interpreted as 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:
  • services (Union[Services, str]) – Specifies the services that the Shared Access Signature (sas) token will be able to be utilized with. Will default to only this package (i.e. fileshare) if not provided.

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

  • sts_hook (Optional[Callable[[str], None]]) – For debugging purposes only. If provided, the hook is called with the string to sign that was used to generate the SAS.

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_file_sas(account_name: str, share_name: str, file_path: List[str], account_key: str, permission: FileSasPermissions | str | None = None, expiry: datetime | str | None = None, start: datetime | str | None = None, policy_id: str | None = None, ip: str | None = None, *, sts_hook: Callable[[str], None] | None = None, **kwargs: Any) str[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 or str or None) – The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions. Permissions must be ordered rcwd. 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 or None) – 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 or None) – 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. The provided datetime will always be interpreted as UTC.

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

  • ip (Optional[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.

  • sts_hook (Optional[Callable[[str], None]]) – For debugging purposes only. If provided, the hook is called with the string to sign that was used to generate the SAS.

Returns:

A Shared Access Signature (sas) token.

Return type:

str

azure.storage.fileshare.generate_share_sas(account_name: str, share_name: str, account_key: str, permission: ShareSasPermissions | str | None = None, expiry: datetime | str | None = None, start: datetime | str | None = None, policy_id: str | None = None, ip: str | None = None, *, sts_hook: Callable[[str], None] | None = None, **kwargs: Any) str[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 or str or None) – The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions. Permissions must be ordered rcwdl. 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 or None) – 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 or None) – 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. The provided datetime will always be interpreted as UTC.

  • policy_id (Optional[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 (Optional[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.

  • sts_hook (Optional[Callable[[str], None]]) – For debugging purposes only. If provided, the hook is called with the string to sign that was used to generate the SAS.

Returns:

A Shared Access Signature (sas) token.

Return type:

str

Subpackages