ShareClient Class

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.

Inheritance
azure.storage.fileshare._shared.base_client.StorageAccountHostsMixin
ShareClient

Constructor

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)

Parameters

account_url
str
Required

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
Required

The name of the share with which to interact.

snapshot
str
default value: None

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

credential
default value: 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.
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.

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

Methods

acquire_lease

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.

New in version 12.5.0.

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

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

create_permission_for_share

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.

create_share

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

create_snapshot

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.

delete_directory

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

delete_share

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

from_connection_string

Create ShareClient from a Connection String.

from_share_url
get_directory_client

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

get_file_client

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

get_permission_for_share

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

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

get_share_access_policy

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

get_share_properties

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.

get_share_stats

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.

list_directories_and_files

Lists the directories and files under the share.

set_share_access_policy

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.

set_share_metadata

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.

set_share_properties

Sets the share properties.

New in version 12.4.0.

set_share_quota

Sets the quota for the share.

acquire_lease

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.

New in version 12.5.0.

acquire_lease(**kwargs: Any) -> ShareLeaseClient

Parameters

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

Examples

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.

close()

create_directory

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

create_directory(directory_name: str, **kwargs: Any) -> ShareDirectoryClient

Parameters

directory_name
str
Required

The name of the directory.

metadata

Name-value pairs associated with the directory as metadata.

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

ShareDirectoryClient

Return type

create_permission_for_share

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.

create_permission_for_share(file_permission: str, **kwargs: Any) -> str

Parameters

file_permission
str
Required

File permission, a Portable SDDL

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 file permission key

Return type

str

create_share

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

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

Parameters

metadata
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'

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

Returns

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

Return type

<xref:Dict>[str, <xref:Any>]

Examples

Creates a file share.


   # Create share with Access Tier set to Hot
   share.create_share(access_tier=ShareAccessTier("Hot"))

create_snapshot

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.

create_snapshot(**kwargs: Any | None) -> Dict[str, Any]

Parameters

metadata
dict(str,str)

Name-value pairs associated with the share as metadata.

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

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

Return type

dict[str, <xref:Any>]

Examples

Creates a snapshot of the file share.


   share.create_snapshot()

delete_directory

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

delete_directory(directory_name: str, **kwargs: Any) -> None

Parameters

directory_name
str
Required

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

Return type

delete_share

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

delete_share(delete_snapshots: bool | None = False, **kwargs) -> None

Parameters

delete_snapshots
bool
Required

Indicates if snapshots are to be deleted.

lease

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

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

Examples

Deletes the share and any snapshots.


   share.delete_share(delete_snapshots=True)

from_connection_string

Create ShareClient from a Connection String.

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

Parameters

conn_str
str
Required

A connection string to an Azure Storage account.

share_name
str
Required

The name of the share.

snapshot
str
default value: None

The optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from create_snapshot.

credential
default value: 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

Examples

Gets the share client from connection string.


   from azure.storage.fileshare import ShareClient
   share = ShareClient.from_connection_string(self.connection_string, "sharesamples2")

from_share_url

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

Parameters

share_url
str
Required

The full URI to the share.

snapshot
str
default value: None

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

credential
default value: 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

get_directory_client

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

get_directory_client(directory_path: str | None = None) -> ShareDirectoryClient

Parameters

directory_path
str
default value: None

Path to the specified directory.

Returns

A Directory Client.

Return type

get_file_client

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

get_file_client(file_path: str) -> ShareFileClient

Parameters

file_path
str
Required

Path to the specified file.

Returns

A File Client.

Return type

get_permission_for_share

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

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

get_permission_for_share(permission_key: str, **kwargs: Any) -> str

Parameters

permission_key
str
Required

Key of the file permission to retrieve

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 file permission (a portable SDDL)

Return type

str

get_share_access_policy

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

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

Parameters

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.

New 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, <xref:Any>]

get_share_properties

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.

get_share_properties(**kwargs: Any) -> ShareProperties

Parameters

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.

New in version 12.5.0.

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

Returns

The share properties.

Return type

Examples

Gets the share properties.


   properties = share.get_share_properties()

get_share_stats

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.

get_share_stats(**kwargs: Any) -> int

Parameters

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.

New 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

Lists the directories and files under the share.

list_directories_and_files(directory_name: str | None = None, name_starts_with: str | None = None, marker: str | None = None, **kwargs: Any) -> Iterable[Dict[str, str]]

Parameters

directory_name
str
Required

Name of a directory.

name_starts_with
str
Required

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

marker
str
Required

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.

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

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

New 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

<xref:Iterable>[<xref:Dict>[<xref:str,str>]]

Examples

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

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.

set_share_access_policy(signed_identifiers: Dict[str, AccessPolicy], **kwargs: Any) -> Dict[str, str]

Parameters

signed_identifiers
dict(str, AccessPolicy)
Required

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.

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.

New 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, <xref:Any>)

set_share_metadata

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.

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

Parameters

metadata
dict(str, str)
Required

Name-value pairs associated with the share as metadata.

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.

New 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, <xref:Any>)

Examples

Sets the share metadata.


   data = {'category': 'test'}
   share.set_share_metadata(metadata=data)

set_share_properties

Sets the share properties.

New in version 12.4.0.

set_share_properties(**kwargs: Any) -> Dict[str, Any]

Parameters

access_tier
str or <xref:azure.storage.fileshare.models.ShareAccessTier>

Specifies the access tier of the share. Possible values: 'TransactionOptimized', 'Hot', and 'Cool'

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.

Returns

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

Return type

dict(str, <xref:Any>)

Examples

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

Sets the quota for the share.

set_share_quota(quota: int, **kwargs: Any) -> Dict[str, Any]

Parameters

quota
int
Required

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.

lease

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

New 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, <xref:Any>)

Examples

Sets the share quota.


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

Attributes

api_version

The version of the Storage API used for requests.

location_mode

The location mode that the client is currently using.

By default this will be "primary". Options include "primary" and "secondary".

primary_endpoint

The full primary endpoint URL.

primary_hostname

The hostname of the primary endpoint.

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.

Exceptions

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.

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. :rtype: str