ShareServiceClient Class

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.

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

Constructor

ShareServiceClient(account_url: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, *, token_intent: Literal['backup'] | None = None, **kwargs: Any)

Parameters

Name Description
account_url
Required
str

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

credential

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

Keyword-Only Parameters

Name Description
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

If true, the trailing dot will not be trimmed from the target URI.

allow_source_trailing_dot

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.

Examples

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
   )

Methods

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

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.

delete_share

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

from_connection_string

Create ShareServiceClient from a Connection String.

get_service_properties

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

get_share_client

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

list_shares

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.

set_service_properties

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.

undelete_share

Restores soft-deleted share.

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

New in version 12.2.0: This operation was introduced in API version '2019-12-12'.

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_share

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.

create_share(share_name: str, **kwargs) -> ShareClient

Parameters

Name Description
share_name
Required
str

The name of the share to create.

Keyword-Only Parameters

Name Description
metadata

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.

Returns

Type Description

A ShareClient for the newly created Share.

Examples

Create a share in the file share service.


   file_service.create_share(share_name="fileshare1")

delete_share

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

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

Parameters

Name Description
share_name
Required

The share to delete. This can either be the name of the share, or an instance of ShareProperties.

delete_snapshots
Required

Indicates if snapshots are to be deleted.

Keyword-Only Parameters

Name Description
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

Type Description

Examples

Delete a share in the file share service.


   file_service.delete_share(share_name="fileshare1")

from_connection_string

Create ShareServiceClient from a Connection String.

from_connection_string(conn_str: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any) -> Self

Parameters

Name Description
conn_str
Required
str

A connection string to an Azure Storage account.

credential

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

Returns

Type Description

A File Share service client.

Examples

Create the share service client with connection string.


   from azure.storage.fileshare import ShareServiceClient
   share_service_client = ShareServiceClient.from_connection_string(self.connection_string)

get_service_properties

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

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

Keyword-Only Parameters

Name Description
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

Type Description

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

Examples

Get file share service properties.


   properties = file_service.get_service_properties()

get_share_client

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

get_share_client(share: ShareProperties | str, snapshot: Dict[str, Any] | str | None = None) -> ShareClient

Parameters

Name Description
share
Required

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 <xref:azure.storage.fileshare.create_snapshot>.

default value: None

Returns

Type Description

A ShareClient.

Examples

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

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.

list_shares(name_starts_with: str | None = None, include_metadata: bool | None = False, include_snapshots: bool | None = False, **kwargs) -> ItemPaged[ShareProperties]

Parameters

Name Description
name_starts_with
Required
str

Filters the results to return only shares whose names begin with the specified name_starts_with.

include_metadata
Required

Specifies that share metadata be returned in the response.

include_snapshots
Required

Specifies that share snapshot be returned in the response.

Keyword-Only Parameters

Name Description
include_deleted

Specifies that deleted shares be returned in the response. This is only for share soft delete enabled account.

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

Type Description

An iterable (auto-paging) of ShareProperties.

Examples

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

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.

set_service_properties(hour_metrics: Metrics | None = None, minute_metrics: Metrics | None = None, cors: List[CorsRule] | None = None, protocol: ShareProtocolSettings | None = None, **kwargs) -> None

Parameters

Name Description
hour_metrics
Required

The hour metrics settings provide a summary of request statistics grouped by API in hourly aggregates for files.

minute_metrics
Required

The minute metrics settings provide request statistics for each minute for files.

cors
Required
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
Required

Sets protocol settings

Keyword-Only Parameters

Name Description
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

Type Description

Examples

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

Restores soft-deleted share.

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

New in version 12.2.0: This operation was introduced in API version '2019-12-12'.

undelete_share(deleted_share_name: str, deleted_share_version: str, **kwargs: Any) -> ShareClient

Parameters

Name Description
deleted_share_name
Required
str

Specifies the name of the deleted share to restore.

deleted_share_version
Required
str

Specifies the version of the deleted share to restore.

Keyword-Only Parameters

Name Description
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

Type Description

A ShareClient for the undeleted Share.

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

Type Description

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