Azure File Share storage client library for Python
npx @tessl/cli install tessl/pypi-azure-storage-file-share@12.22.0Azure Storage File Share provides fully managed file shares in the cloud that are accessible via the industry standard Server Message Block (SMB) protocol or Network File System (NFS) protocol. The Azure Storage File Share Python SDK (azure-storage-file-share) enables developers to programmatically interact with Azure File Shares using Python applications.
Key capabilities include:
pip install azure-storage-file-share# Main synchronous clients
from azure.storage.fileshare import (
ShareServiceClient,
ShareClient,
ShareDirectoryClient,
ShareFileClient,
ShareLeaseClient
)
# Async clients
from azure.storage.fileshare.aio import (
ShareServiceClient as AsyncShareServiceClient,
ShareClient as AsyncShareClient,
ShareDirectoryClient as AsyncShareDirectoryClient,
ShareFileClient as AsyncShareFileClient,
ShareLeaseClient as AsyncShareLeaseClient
)
# SAS generation functions
from azure.storage.fileshare import (
generate_account_sas,
generate_share_sas,
generate_file_sas
)
# Models and properties
from azure.storage.fileshare import (
ShareProperties,
FileProperties,
DirectoryProperties,
ContentSettings,
Handle,
Metrics,
RetentionPolicy,
CorsRule,
ShareSmbSettings,
ShareAccessTier,
SmbMultichannel,
ShareProtocolSettings,
AccessPolicy,
ShareSasPermissions,
FileSasPermissions,
NTFSAttributes,
ShareProtocols,
ShareRootSquash
)
# Retry policies and shared models
from azure.storage.fileshare import (
ExponentialRetry,
LinearRetry,
LocationMode,
ResourceTypes,
AccountSasPermissions,
StorageErrorCode,
Services
)
# Credentials and authentication
from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredentialfrom azure.storage.fileshare import ShareServiceClient
from azure.core.credentials import AzureNamedKeyCredential
# Option 1: Connection string (recommended for development)
service_client = ShareServiceClient.from_connection_string(
conn_str="DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey;EndpointSuffix=core.windows.net"
)
# Option 2: Account URL + Named Key Credential
credential = AzureNamedKeyCredential("myaccount", "mykey")
service_client = ShareServiceClient(
account_url="https://myaccount.file.core.windows.net",
credential=credential
)
# Option 3: SAS token
service_client = ShareServiceClient(
account_url="https://myaccount.file.core.windows.net",
credential="?sv=2021-06-08&ss=f&srt=sco&sp=rwdlacup&se=..."
)
# Option 4: Azure Active Directory (OAuth)
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
service_client = ShareServiceClient(
account_url="https://myaccount.file.core.windows.net",
credential=credential
)# Create a file share
share_client = service_client.create_share("myshare", quota=100) # 100 GB quota
# Get clients for specific resources
directory_client = share_client.get_directory_client("mydirectory")
file_client = share_client.get_file_client("myfile.txt")
# Upload a file
with open("local_file.txt", "rb") as data:
file_client.upload_file(data, overwrite=True)
# Download a file
download_stream = file_client.download_file()
with open("downloaded_file.txt", "wb") as file_handle:
download_stream.readinto(file_handle)
# List shares
shares = list(service_client.list_shares(include_metadata=True))
for share in shares:
print(f"Share: {share.name}, Quota: {share.quota} GB")
# Create directory structure
directory_client.create_directory()
subdirectory_client = directory_client.create_subdirectory("subdir")
# List directory contents
items = list(directory_client.list_directories_and_files())
for item in items:
print(f"{'Directory' if item.get('is_directory') else 'File'}: {item['name']}")import asyncio
from azure.storage.fileshare.aio import ShareServiceClient
async def main():
async with ShareServiceClient.from_connection_string(conn_str) as service_client:
# Create share
share_client = await service_client.create_share("asyncshare")
# Upload file asynchronously
file_client = share_client.get_file_client("asyncfile.txt")
with open("local_file.txt", "rb") as data:
await file_client.upload_file(data)
# Download file asynchronously
download_stream = await file_client.download_file()
content = await download_stream.readall()
# List shares asynchronously
async for share in service_client.list_shares():
print(f"Share: {share.name}")
# Run async function
asyncio.run(main())The Azure Storage File Share SDK follows a hierarchical client architecture:
ShareServiceClient (Account Level)
├── ShareClient (Share Level)
├── ShareDirectoryClient (Directory Level)
│ ├── ShareFileClient (File Level)
│ └── ShareDirectoryClient (Subdirectory)
└── ShareFileClient (Root File Level)ShareServiceClient: Entry point for account-level operations
ShareClient: Operations on a specific file share
ShareDirectoryClient: Operations on directories
ShareFileClient: Operations on individual files
ShareLeaseClient: Lease management for files and shares
# Get clients from parent clients
share_client = service_client.get_share_client("myshare")
directory_client = share_client.get_directory_client("path/to/directory")
file_client = share_client.get_file_client("path/to/file.txt")
file_client = directory_client.get_file_client("filename.txt")
# Create from URLs
share_client = ShareClient.from_share_url("https://account.file.core.windows.net/share")
directory_client = ShareDirectoryClient.from_directory_url("https://account.file.core.windows.net/share/dir")
file_client = ShareFileClient.from_file_url("https://account.file.core.windows.net/share/file.txt")
# Create from connection strings
share_client = ShareClient.from_connection_string(conn_str, "sharename")
directory_client = ShareDirectoryClient.from_connection_string(conn_str, "share", "dir/path")
file_client = ShareFileClient.from_connection_string(conn_str, "share", "file/path.txt")# File Share Management
shares = service_client.list_shares(include_metadata=True)
share_client = service_client.create_share("myshare", quota=100)
snapshot = share_client.create_snapshot()
# File Operations
file_client.upload_file(data, overwrite=True, max_concurrency=4)
download_stream = file_client.download_file(offset=0, length=1024)
file_client.upload_range(data=b"chunk", offset=1024, length=len(data))
# Directory Management
directory_client.create_directory()
items = directory_client.list_directories_and_files(name_starts_with="prefix")
handles = directory_client.list_handles(recursive=True)
# Access Control & Security
sas_token = generate_share_sas(account_name, share_name, account_key,
permission="r", expiry=datetime.now() + timedelta(hours=1))
lease_client = file_client.acquire_lease()
# Metadata and Properties
share_client.set_share_metadata({"environment": "production"})
file_client.set_http_headers(ContentSettings(content_type="text/plain"))
properties = file_client.get_file_properties()
# Advanced Operations
file_client.copy_file_from_url(source_url)
file_client.resize_file(new_size=2048)
symlink_client = directory_client.create_symlink("link_name", "target_path")from azure.core.exceptions import (
HttpResponseError,
ResourceNotFoundError,
ResourceExistsError,
ClientAuthenticationError
)
try:
file_client.upload_file(data)
except ResourceExistsError:
print("File already exists")
except ResourceNotFoundError:
print("Share or directory not found")
except ClientAuthenticationError:
print("Authentication failed")
except HttpResponseError as e:
print(f"HTTP error: {e.status_code} - {e.error_code}")For complete API documentation, see the individual capability documents linked above.