azure.storage.fileshare.aio package¶
-
class
azure.storage.fileshare.aio.
ShareClient
(account_url: str, share_name: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = 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()
andget_file_client()
functions.- Parameters
account_url (str) – The URI to the storage account. In order to create a client given the full URI to the share, use the
from_share_url()
classmethod.share_name (str) – The name of the share with which to interact.
snapshot (str) – An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from
create_snapshot()
.credential – The 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
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.
-
async
acquire_lease
(**kwargs: Any) → azure.storage.fileshare.aio._lease_async.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.
New 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) – The timeout parameter is expressed in seconds.
- Returns
A ShareLeaseClient object.
- Return type
Example:
-
async
close
()¶ This method is to close the sockets opened by the client. It need not be used when using with a context manager.
-
async
create_directory
(directory_name: str, **kwargs: Any) → azure.storage.fileshare.aio._directory_client_async.ShareDirectoryClient[source]¶ Creates a directory in the share and returns a client to interact with the directory.
-
async
create_permission_for_share
(file_permission: str, **kwargs: Any) → str[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.
-
async
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 (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) – The timeout parameter is expressed in seconds.
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
Dict[str, Any]
Example:
# Create share with Access Tier set to Hot await share.create_share(access_tier=ShareAccessTier("Hot"))
-
async
create_snapshot
(**kwargs: Optional[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
Example:
await share.create_snapshot()
-
async
delete_directory
(directory_name: str, **kwargs: Any) → None[source]¶ Marks the directory for deletion. The directory is later deleted during garbage collection.
-
async
delete_share
(delete_snapshots: Optional[bool] = False, **kwargs) → None[source]¶ Marks the specified share for deletion. The share is later deleted during garbage collection.
- Parameters
delete_snapshots (bool) – Indicates if snapshots are to be deleted.
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
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’.
Example:
await share.delete_share(delete_snapshots=True)
-
classmethod
from_connection_string
(conn_str: str, share_name: str, snapshot: Optional[str] = None, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Any) → ShareClient[source]¶ Create ShareClient from a Connection String.
- Parameters
conn_str (str) – A connection string to an Azure Storage account.
share_name (str) – The name of the share.
snapshot (str) – The optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from
create_snapshot()
.credential – The 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
Example:
from azure.storage.fileshare import ShareClient share = ShareClient.from_connection_string(self.connection_string, "sharesamples2")
-
classmethod
from_share_url
(share_url: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Any) → ShareClient[source]¶ - Parameters
share_url (str) – The full URI to the share.
snapshot (str) – An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from
create_snapshot()
.credential – The 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
(directory_path: Optional[str] = None) → azure.storage.fileshare.aio._directory_client_async.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
-
get_file_client
(file_path: str) → azure.storage.fileshare.aio._file_client_async.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
-
async
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.
-
async
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) – The timeout parameter is expressed in seconds.
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
-
async
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) – The timeout parameter is expressed in seconds.
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
Example:
properties = await share.get_share_properties()
-
async
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) – The timeout parameter is expressed in seconds.
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
-
list_directories_and_files
(directory_name: Optional[str] = None, name_starts_with: Optional[str] = None, marker: Optional[str] = None, **kwargs: Any) → Iterable[Dict[str, str]][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 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) – The timeout parameter is expressed in seconds.
- Returns
An auto-paging iterable of dict-like DirectoryProperties and FileProperties
Example:
# Create a directory in the share dir_client = await share.create_directory("mydir") # Upload a file to the directory with open(SOURCE_FILE, "rb") as source_file: await dir_client.upload_file(file_name="sample", data=source_file) # List files in the directory my_files = [] async for item in share.list_directories_and_files(directory_name="mydir"): my_files.append(item) print(my_files)
-
async
set_share_access_policy
(signed_identifiers: Dict[str, AccessPolicy], **kwargs: Any) → Dict[str, str][source]¶ Sets the permissions for the share, or stored access policies that may be used with Shared Access Signatures. The permissions indicate whether files in a share may be accessed publicly.
- Parameters
signed_identifiers (dict(str,
AccessPolicy
)) – A dictionary of access policies to associate with the share. The dictionary may contain up to 5 elements. An empty dictionary will clear the access policies set on the service.- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
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
-
async
set_share_metadata
(metadata: Dict[str, Any], **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) – The timeout parameter is expressed in seconds.
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
Example:
data = {'category': 'test'} await share.set_share_metadata(metadata=data)
-
async
set_share_properties
(**kwargs: Any) → Dict[str, Any][source]¶ Sets the share properties.
New in version 12.3.0.
- Keyword Arguments
access_tier (str or 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) – The timeout parameter is expressed in seconds.
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
Example:
# Set the tier for the first share to Hot await share1.set_share_properties(access_tier="Hot") # Set the quota for the first share to 3 await share1.set_share_properties(quota=3) # Set the tier for the second share to Cool and quota to 2 await share2.set_share_properties(access_tier=ShareAccessTier("Cool"), quota=2) # Get the shares' properties props1 = await share1.get_share_properties() props2 = await share2.get_share_properties() print(props1.access_tier) print(props1.quota) print(props2.access_tier) print(props2.quota)
-
async
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) – The timeout parameter is expressed in seconds.
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
Example:
# Set the quota for the share to 1GB await share.set_share_quota(quota=1)
-
property
location_mode
¶ The location mode that the client is currently using.
By default this will be “primary”. Options include “primary” and “secondary”.
- Type
-
property
secondary_endpoint
¶ The full secondary endpoint URL if configured.
If not available a ValueError will be raised. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.
- Type
- Raises
-
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.
-
property
url
¶ The full endpoint URL to this entity, including SAS token if used.
This could be either the primary endpoint, or the secondary endpoint depending on the current
location_mode()
.
-
class
azure.storage.fileshare.aio.
ShareDirectoryClient
(account_url: str, share_name: str, directory_path: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Optional[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()
andget_file_client()
functions.- Parameters
account_url (str) – The URI to the storage account. In order to create a client given the full URI to the directory, use the
from_directory_url()
classmethod.share_name (str) – The name of the share for the directory.
directory_path (str) – The directory path for the directory with which to interact. If specified, this value will override a directory value specified in the directory URL.
snapshot (str) – An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from
ShareClient.create_snapshot()
.credential – The 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
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.
-
async
close
()¶ This method is to close the sockets opened by the client. It need not be used when using with a context manager.
-
async
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) – The timeout parameter is expressed in seconds.
- 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
-
async
close_handle
(handle: Union[str, HandleItem], **kwargs: Any) → Dict[str, int][source]¶ Close an open file handle.
- Parameters
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
The number of handles closed (this may be 0 if the specified handle was not found) and the number of handles failed to close in a dict.
- Return type
-
async
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
) – 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 directory. Default value: “now”.
file_last_write_time (str or datetime) – Last write time for the directory. 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 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_change_time (str or datetime) –
Change time for the directory. If not specified, change time will be set to the current date/time.
New in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.
metadata (dict(str,str)) – Name-value pairs associated with the directory as metadata.
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
Directory-updated property dict (Etag and last modified).
- Return type
Example:
await directory.create_directory()
-
async
create_subdirectory
(directory_name: str, **kwargs) → azure.storage.fileshare.aio._directory_client_async.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
Example:
# Create the directory await parent_dir.create_directory() # Create a subdirectory subdir = await parent_dir.create_subdirectory("subdir")
-
async
delete_directory
(**kwargs: Any) → None[source]¶ Marks the directory for deletion. The directory is later deleted during garbage collection.
Example:
await directory.delete_directory()
-
async
delete_file
(file_name: str, **kwargs: Optional[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) – The timeout parameter is expressed in seconds.
- Return type
Example:
# Delete the file in the directory await directory.delete_file(file_name="sample")
-
async
delete_subdirectory
(directory_name: str, **kwargs) → None[source]¶ Deletes a subdirectory.
- Parameters
directory_name (str) – The name of the subdirectory.
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
- Return type
Example:
await parent_dir.delete_subdirectory("subdir")
-
async
exists
(**kwargs: Any) → bool[source]¶ Returns True if a directory exists and returns False otherwise.
-
classmethod
from_connection_string
(conn_str: str, share_name: str, directory_path: str, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Any) → ShareDirectoryClient[source]¶ Create ShareDirectoryClient from a Connection String.
- Parameters
conn_str (str) – A connection string to an Azure Storage account.
share_name (str) – The name of the share.
directory_path (str) – The directory path.
credential – The 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 directory client.
- Return type
-
classmethod
from_directory_url
(directory_url: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Optional[Any]) → ShareDirectoryClient[source]¶ Create a ShareDirectoryClient from a directory url.
- Parameters
directory_url (str) – The full URI to the directory.
snapshot (str) – An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from
ShareClient.create_snapshot()
.credential –
The 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 directory client. :rtype: ~azure.storage.fileshare.ShareDirectoryClient
-
async
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) – The timeout parameter is expressed in seconds.
- Returns
DirectoryProperties
- Return type
-
get_file_client
(file_name: str, **kwargs: Any) → azure.storage.fileshare.aio._file_client_async.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
-
get_subdirectory_client
(directory_name: str, **kwargs: Any) → azure.storage.fileshare.aio._directory_client_async.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
Example:
# Get a directory client and create the directory parent = share.get_directory_client("dir1") await parent.create_directory() # Get a subdirectory client and create the subdirectory "dir1/dir2" subdirectory = parent.get_subdirectory_client("dir2") await subdirectory.create_directory()
-
list_directories_and_files
(name_starts_with: Optional[str] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[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 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) – The timeout parameter is expressed in seconds.
- Returns
An auto-paging iterable of dict-like DirectoryProperties and FileProperties
- Return type
AsyncItemPaged[DirectoryProperties and FileProperties]
Example:
# List the directories and files under the parent directory my_list = [] async for item in parent_dir.list_directories_and_files(): my_list.append(item) print(my_list)
-
list_handles
(recursive: bool = False, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[source]¶ Lists opened handles on a directory or a file under the directory.
- Parameters
recursive (bool) – Boolean that specifies if operation should apply to the directory specified by the client, its files, its subdirectories and their files. Default value is False.
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
An auto-paging iterable of HandleItem
- Return type
-
async
rename_directory
(new_name: str, **kwargs: Any) → azure.storage.fileshare.aio._directory_client_async.ShareDirectoryClient[source]¶ Rename the source directory.
- Parameters
new_name (str) – The new directory name.
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
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_attributes – The file system attributes for the directory.
:paramtype file_attributes:~azure.storage.fileshare.NTFSAttributes or str :keyword file_creation_time:
Creation time for the directory.
:paramtype file_creation_time:~datetime.datetime or str :keyword file_last_write_time:
Last write time for the file.
:paramtype file_last_write_time:~datetime.datetime or str :keyword file_change_time:
Change time for the directory. If not specified, change time will be set to the current date/time.
New in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.
- Keyword Arguments
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
-
async
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.
-
async
set_http_headers
(file_attributes: Union[str, NTFSAttributes] = 'none', file_creation_time: Optional[Union[str, datetime]] = 'preserve', file_last_write_time: Optional[Union[str, datetime]] = 'preserve', file_permission: Optional[str] = None, permission_key: Optional[str] = None, **kwargs: Any) → Dict[str, Any][source]¶ Sets HTTP headers on the directory.
- Parameters
file_attributes (str or
NTFSAttributes
) – The file system attributes for files and directories. If not set, indicates preservation of existing values. Here is an example for when the var type is str: ‘Temporary|Archive’file_creation_time (str or datetime) – Creation time for the file Default value: Preserve.
file_last_write_time (str or datetime) – Last write time for the file Default value: Preserve.
file_permission (str) – If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.
permission_key (str) – Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.
- Keyword Arguments
- Returns
File-updated property dict (Etag and last modified).
- Return type
-
async
upload_file
(file_name: str, data: Any, length: Optional[int] = None, **kwargs: Any) → azure.storage.fileshare.aio._file_client_async.ShareFileClient[source]¶ Creates a new file in the directory and returns a ShareFileClient to interact with the file.
- Parameters
- Keyword Arguments
metadata (dict(str,str)) – Name-value pairs associated with the file as metadata.
content_settings (ContentSettings) – ContentSettings object used to set file properties. Used to set content type, encoding, language, disposition, md5, and cache control.
validate_content (bool) – If true, calculates an MD5 hash for each range of the file. The storage service checks the hash of the content that has arrived with the hash that was sent. This is primarily valuable for detecting bitflips on the wire if using http instead of https as https (the default) will already validate. Note that this MD5 hash is not stored with the file.
max_concurrency (int) – Maximum number of parallel connections to use.
progress_hook (Callable[[int, Optional[int]], Awaitable[None]]) – An async 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) – The timeout parameter is expressed in seconds.
encoding (str) – Defaults to UTF-8.
- Returns
ShareFileClient
- Return type
Example:
# Upload a file to the directory with open(SOURCE_FILE, "rb") as source: await directory.upload_file(file_name="sample", data=source)
-
property
location_mode
¶ The location mode that the client is currently using.
By default this will be “primary”. Options include “primary” and “secondary”.
- Type
-
property
secondary_endpoint
¶ The full secondary endpoint URL if configured.
If not available a ValueError will be raised. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.
- Type
- Raises
-
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.
-
property
url
¶ The full endpoint URL to this entity, including SAS token if used.
This could be either the primary endpoint, or the secondary endpoint depending on the current
location_mode()
.
-
class
azure.storage.fileshare.aio.
ShareFileClient
(account_url: str, share_name: str, file_path: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Any)[source]¶ A client to interact with a specific file, although that file may not yet exist.
- Parameters
account_url (str) – The URI to the storage account. In order to create a client given the full URI to the file, use the
from_file_url()
classmethod.share_name (str) – The name of the share for the file.
file_path (str) – The file path to the file with which to interact. If specified, this value will override a file value specified in the file URL.
snapshot (str) – An optional file snapshot on which to operate. This can be the snapshot ID string or the response returned from
ShareClient.create_snapshot()
.credential – The 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
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.
-
async
abort_copy
(copy_id: Union[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
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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Return type
-
async
acquire_lease
(lease_id: Optional[str] = None, **kwargs: Any) → azure.storage.fileshare.aio._lease_async.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) – The timeout parameter is expressed in seconds.
- Returns
A ShareLeaseClient object.
- Return type
Example:
-
async
clear_range
(offset: int, length: int, **kwargs) → Dict[str, Any][source]¶ Clears the specified range and releases the space used in storage for that range.
- Parameters
- Keyword Arguments
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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
File-updated property dict (Etag and last modified).
- Return type
Dict[str, Any]
-
async
close
()¶ This method is to close the sockets opened by the client. It need not be used when using with a context manager.
-
async
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.
-
async
close_handle
(handle: Union[str, HandleItem], **kwargs: Any) → Dict[str, int][source]¶ Close an open file handle.
- Parameters
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
The number of handles closed (this may be 0 if the specified handle was not found) and the number of handles failed to close in a dict.
- Return type
-
async
create_file
(size: int, file_attributes: Union[str, NTFSAttributes] = 'none', file_creation_time: Optional[Union[str, datetime]] = 'now', file_last_write_time: Optional[Union[str, datetime]] = 'now', file_permission: Optional[str] = None, permission_key: Optional[str] = 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
) – 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.
New 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 (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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
File-updated property dict (Etag and last modified).
- Return type
Example:
# Create and allocate bytes for the file (no content added yet) await my_allocated_file.create_file(size=100)
-
async
delete_file
(**kwargs: Any) → None[source]¶ Marks the specified file for deletion. The file is later deleted during garbage collection.
- Keyword Arguments
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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Return type
Example:
await my_file.delete_file()
-
async
download_file
(offset: Optional[int] = None, length: Optional[int] = None, **kwargs: Any) → azure.storage.fileshare.aio._download_async.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 async iterator which allows the user to iterate over the content in chunks.
- Parameters
- Keyword Arguments
max_concurrency (int) – Maximum number of parallel connections to use.
validate_content (bool) – If true, calculates an MD5 hash for each chunk of the file. The storage service checks the hash of the content that has arrived with the hash that was sent. This is primarily valuable for detecting bitflips on the wire if using http instead of https as https (the default) will already validate. Note that this MD5 hash is not stored with the file. Also note that if enabled, the memory-efficient upload algorithm will not be used, because computing the MD5 hash requires buffering entire blocks, and doing so defeats the purpose of the memory-efficient algorithm.
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.
New in version 12.1.0.
progress_hook (Callable[[int, int], Awaitable[None]]) – An async 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 size of the blob or None if the size is unknown.
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
A streaming object (StorageStreamDownloader)
- Return type
StorageStreamDownloader
Example:
with open(DEST_FILE, "wb") as data: stream = await my_file.download_file() data.write(await stream.readall())
-
classmethod
from_connection_string
(conn_str: str, share_name: str, file_path: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Any) → ShareFileClient[source]¶ Create ShareFileClient from a Connection String.
- Parameters
conn_str (str) – A connection string to an Azure Storage account.
share_name (str) – The name of the share.
file_path (str) – The file path.
snapshot (str) – An optional file snapshot on which to operate. This can be the snapshot ID string or the response returned from
ShareClient.create_snapshot()
.credential – The 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 client.
- Return type
Example:
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: Optional[Union[str, Dict[str, Any]]] = None, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Any) → ShareFileClient[source]¶ A client to interact with a specific file, although that file may not yet exist.
- Parameters
file_url (str) – The full URI to the file.
snapshot (str) – An optional file snapshot on which to operate. This can be the snapshot ID string or the response returned from
ShareClient.create_snapshot()
.credential – The 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 client.
- Return type
-
async
get_file_properties
(**kwargs: Any) → FileProperties[source]¶ Returns all user-defined metadata, standard HTTP properties, and system properties for the file.
- Keyword Arguments
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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
FileProperties
- Return type
-
async
get_ranges
(offset: Optional[int] = None, length: Optional[int] = None, **kwargs: Any) → List[Dict[str, int]][source]¶ Returns the list of valid page ranges for a file or snapshot of a file.
- Parameters
- Keyword Arguments
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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
A list of valid ranges.
- Return type
-
async
get_ranges_diff
(previous_sharesnapshot: Union[str, Dict[str, Any]], offset: Optional[int] = None, length: Optional[int] = 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.
New 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
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) – The timeout parameter is expressed in seconds.
- 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
-
list_handles
(**kwargs: Any) → azure.core.async_paging.AsyncItemPaged[source]¶ Lists handles for file.
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
An auto-paging iterable of HandleItem
- Return type
-
async
rename_file
(new_name: str, **kwargs: Any) → azure.storage.fileshare.aio._file_client_async.ShareFileClient[source]¶ Rename the source file.
- Parameters
new_name (str) – The new file name.
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
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_attributes – The file system attributes for the file.
:paramtype file_attributes:~azure.storage.fileshare.NTFSAttributes or str :keyword file_creation_time:
Creation time for the file.
:paramtype file_creation_time:~datetime.datetime or str :keyword file_last_write_time:
Last write time for the file.
:paramtype file_last_write_time:~datetime.datetime or str :keyword file_change_time:
Change time for the file. If not specified, change time will be set to the current date/time.
New in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.
- Keyword Arguments
content_type (str) –
The Content Type of the new file.
New 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
-
async
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
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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
File-updated property dict (Etag and last modified).
- Return type
Dict[str, Any]
-
async
set_file_metadata
(metadata: Optional[Dict[str, Any]] = 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
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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
File-updated property dict (Etag and last modified).
- Return type
-
async
set_http_headers
(content_settings: ContentSettings, file_attributes: Union[str, NTFSAttributes] = 'preserve', file_creation_time: Optional[Union[str, datetime]] = 'preserve', file_last_write_time: Optional[Union[str, datetime]] = 'preserve', file_permission: Optional[str] = None, permission_key: Optional[str] = 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
) – The file system attributes for files and directories. If not set, indicates preservation of existing values. Here is an example for when the var type is str: ‘Temporary|Archive’file_creation_time (str or datetime) – Creation time for the file Default value: Preserve.
file_last_write_time (str or datetime) – Last write time for the file Default value: Preserve.
file_permission (str) – If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.
permission_key (str) – Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.
- Keyword Arguments
file_change_time (str or datetime) –
Change time for the file. If not specified, change time will be set to the current date/time.
New 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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
File-updated property dict (Etag and last modified).
- Return type
-
async
start_copy_from_url
(source_url: str, **kwargs: Any) → 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.
New 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.
New in version 12.1.0: This parameter was introduced in API version ‘2019-07-07’.
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”.
New 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.
New 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.
New 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.
New 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.
New 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.
New in version 12.1.0: This parameter was introduced in API version ‘2019-07-07’.
metadata – 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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Return type
Example:
await destination_file.start_copy_from_url(source_url=source_url)
-
async
upload_file
(data: Any, length: Optional[int] = None, file_attributes: Union[str, NTFSAttributes] = 'none', file_creation_time: Optional[Union[str, datetime]] = 'now', file_last_write_time: Optional[Union[str, datetime]] = 'now', file_permission: Optional[str] = None, permission_key: Optional[str] = None, **kwargs: Any) → Dict[str, Any][source]¶ Uploads a new file.
- Parameters
data (Any) – Content of the file.
length (int) – Length of the file in bytes. Specify its maximum size, up to 1 TiB.
file_attributes (str or NTFSAttributes) – The file system attributes for files and directories. If not set, the default value would be “None” and the attributes will be set to “Archive”. Here is an example for when the var type is str: ‘Temporary|Archive’. file_attributes value is not case sensitive.
file_creation_time (str or datetime) – Creation time for the file Default value: Now.
file_last_write_time (str or datetime) – Last write time for the file Default value: Now.
file_permission (str) – If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.
permission_key (str) – Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.
- Keyword Arguments
file_change_time (str or datetime) –
Change time for the file. If not specified, change time will be set to the current date/time.
New in version 12.8.0: This parameter was introduced in API version ‘2021-06-08’.
metadata (dict(str,str)) – Name-value pairs associated with the file as metadata.
content_settings (ContentSettings) – ContentSettings object used to set file properties. Used to set content type, encoding, language, disposition, md5, and cache control.
validate_content (bool) – If true, calculates an MD5 hash for each range of the file. The storage service checks the hash of the content that has arrived with the hash that was sent. This is primarily valuable for detecting bitflips on the wire if using http instead of https as https (the default) will already validate. Note that this MD5 hash is not stored with the file.
max_concurrency (int) – Maximum number of parallel connections to use.
encoding (str) – Defaults to UTF-8.
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.
New in version 12.1.0.
progress_hook (Callable[[int, Optional[int]], Awaitable[None]]) – An async 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) – The timeout parameter is expressed in seconds.
- Returns
File-updated property dict (Etag and last modified).
- Return type
Example:
with open(SOURCE_FILE, "rb") as source: await my_file.upload_file(source)
-
async
upload_range
(data: bytes, offset: int, length: int, **kwargs) → Dict[str, Any][source]¶ Upload a range of bytes to a file.
- Parameters
- 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.
New 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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
encoding (str) – Defaults to UTF-8.
- Returns
File-updated property dict (Etag and last modified).
- Return type
Dict[str, Any]
-
async
upload_range_from_url
(source_url: 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.
New 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.
New in version 12.1.0.
timeout (int) – The timeout parameter is expressed in seconds.
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.
-
property
location_mode
¶ The location mode that the client is currently using.
By default this will be “primary”. Options include “primary” and “secondary”.
- Type
-
property
secondary_endpoint
¶ The full secondary endpoint URL if configured.
If not available a ValueError will be raised. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.
- Type
- Raises
-
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.
-
property
url
¶ The full endpoint URL to this entity, including SAS token if used.
This could be either the primary endpoint, or the secondary endpoint depending on the current
location_mode()
.
-
class
azure.storage.fileshare.aio.
ShareLeaseClient
(client: Union[ShareFileClient, ShareClient], lease_id: Optional[str] = None)[source]¶ Creates a new ShareLeaseClient.
This client provides lease operations on a ShareClient or ShareFileClient.
- Variables
id (str) – The ID of the lease currently being maintained. This will be None if no lease has yet been acquired.
etag (str) – The ETag of the lease currently being maintained. This will be None if no lease has yet been acquired or modified.
last_modified (datetime) – The last modified timestamp of the lease currently being maintained. This will be None if no lease has yet been acquired or modified.
- 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.
-
async
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) – The timeout parameter is expressed in seconds.
- Return type
-
async
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.
New in version 12.5.0.
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
Approximate time remaining in the lease period, in seconds.
- Return type
-
async
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.
-
async
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) – The timeout parameter is expressed in seconds.
- Returns
None
-
async
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.
New in version 12.6.0.
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
- Returns
None
-
class
azure.storage.fileshare.aio.
ShareServiceClient
(account_url: str, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = 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.- Parameters
account_url (str) – The URL to the file share storage account. Any other entities included in the URL path (e.g. share or file) will be discarded. This URL can be optionally authenticated with a SAS token.
credential – The 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
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.
Example:
from azure.storage.fileshare.aio import ShareServiceClient share_service_client = ShareServiceClient( account_url=self.account_url, credential=self.access_key )
-
async
close
()¶ This method is to close the sockets opened by the client. It need not be used when using with a context manager.
-
async
create_share
(share_name: str, **kwargs) → azure.storage.fileshare.aio._share_client_async.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
- Return type
Example:
await file_service.create_share(share_name="fileshare1")
-
async
delete_share
(share_name: Union[ShareProperties, str], delete_snapshots: Optional[bool] = False, **kwargs) → 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) – The timeout parameter is expressed in seconds.
- Return type
Example:
await file_service.delete_share(share_name="fileshare1")
-
classmethod
from_connection_string
(conn_str: str, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Any) → ShareServiceClient[source]¶ Create ShareServiceClient from a Connection String.
- Parameters
conn_str (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.
- Returns
A File Share service client.
- Return type
Example:
from azure.storage.fileshare import ShareServiceClient share_service_client = ShareServiceClient.from_connection_string(self.connection_string)
-
async
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) – The timeout parameter is expressed in seconds.
- Returns
A dictionary containing file service properties such as analytics logging, hour/minute metrics, cors rules, etc.
- Return type
Dict[str, Any]
Example:
properties = await file_service.get_service_properties()
-
get_share_client
(share: Union[ShareProperties, str], snapshot: Optional[Union[Dict[str, Any], str]] = 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
Example:
from azure.storage.fileshare.aio import ShareServiceClient file_service = ShareServiceClient.from_connection_string(self.connection_string) # Get a share client to interact with a specific share share = file_service.get_share_client("fileshare2")
-
list_shares
(name_starts_with: Optional[str] = None, include_metadata: Optional[bool] = False, include_snapshots: Optional[bool] = False, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[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
- Keyword Arguments
- Returns
An iterable (auto-paging) of ShareProperties.
- Return type
Example:
# List the shares in the file service my_shares = [] async for s in file_service.list_shares(): my_shares.append(s) # Print the shares for share in my_shares: print(share)
-
async
set_service_properties
(hour_metrics: Optional[Metrics] = None, minute_metrics: Optional[Metrics] = None, cors: Optional[List[CorsRule]] = None, protocol: Optional[ShareProtocolSettings], = None, **kwargs) → 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_settings – Sets protocol settings
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
- Return type
Example:
# Create service properties from azure.storage.fileshare import Metrics, CorsRule, RetentionPolicy # Create metrics for requests statistics hour_metrics = Metrics(enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5)) minute_metrics = Metrics(enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5)) # Create CORS rules cors_rule1 = CorsRule(['www.xyz.com'], ['GET']) allowed_origins = ['www.xyz.com', "www.ab.com", "www.bc.com"] allowed_methods = ['GET', 'PUT'] max_age_in_seconds = 500 exposed_headers = ["x-ms-meta-data*", "x-ms-meta-source*", "x-ms-meta-abc", "x-ms-meta-bcd"] allowed_headers = ["x-ms-meta-data*", "x-ms-meta-target*", "x-ms-meta-xyz", "x-ms-meta-foo"] cors_rule2 = CorsRule( allowed_origins, allowed_methods, max_age_in_seconds=max_age_in_seconds, exposed_headers=exposed_headers, allowed_headers=allowed_headers) cors = [cors_rule1, cors_rule2] async with file_service: # Set the service properties await file_service.set_service_properties(hour_metrics, minute_metrics, cors)
-
async
undelete_share
(deleted_share_name: str, deleted_share_version: str, **kwargs: Any) → azure.storage.fileshare.aio._share_client_async.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.
New in version 12.2.0: This operation was introduced in API version ‘2019-12-12’.
- Parameters
- Keyword Arguments
timeout (int) – The timeout parameter is expressed in seconds.
- Return type
-
property
location_mode
¶ The location mode that the client is currently using.
By default this will be “primary”. Options include “primary” and “secondary”.
- Type
-
property
secondary_endpoint
¶ The full secondary endpoint URL if configured.
If not available a ValueError will be raised. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.
- Type
- Raises
-
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.
-
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()
.