or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

async-clients.mddirectory-client.mdfile-client.mdindex.mdlease-client.mdmodels.mdsas-generation.mdservice-client.mdshare-client.md
tile.json

tessl/pypi-azure-storage-file-share

Azure File Share storage client library for Python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/azure-storage-file-share@12.22.x

To install, run

npx @tessl/cli install tessl/pypi-azure-storage-file-share@12.22.0

index.mddocs/

Azure Storage File Share Python SDK

Overview

Azure 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:

  • Account-level operations: Manage service properties, list/create/delete shares
  • Share-level operations: Create snapshots, set quotas, manage permissions and metadata
  • Directory operations: Create/delete directories, list contents, manage metadata
  • File operations: Upload/download files, copy operations, range management, lease management
  • Advanced features: SAS token generation, async support, handle management, symbolic links

Package Information

  • Package Name: azure-storage-file-share
  • Package Type: pypi
  • Language: Python
  • Installation: pip install azure-storage-file-share

Core Imports

# 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, AzureSasCredential

Basic Usage

Client Authentication Options

from 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
)

Common Operations

# 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']}")

Async Usage Pattern

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())

Architecture

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)

Client Hierarchy

  1. ShareServiceClient: Entry point for account-level operations

    • Manage service properties and CORS rules
    • List, create, and delete shares
    • Generate account-level SAS tokens
  2. ShareClient: Operations on a specific file share

    • Create snapshots and manage quotas
    • Set share-level permissions and metadata
    • Create directories and files at the root level
  3. ShareDirectoryClient: Operations on directories

    • Create, delete, and list directory contents
    • Manage directory metadata and properties
    • Handle file operations within the directory
  4. ShareFileClient: Operations on individual files

    • Upload, download, copy files
    • Manage file properties and metadata
    • Handle range operations and leases
  5. ShareLeaseClient: Lease management for files and shares

    • Acquire, renew, release, and break leases
    • Change lease IDs

Client Factory Methods

# 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")

Capabilities

Account Management

  • Service Client Operations - Account-level operations, service properties, share management

Share Operations

Directory Management

File Operations

Lease Management

Security & Access Control

Async Programming

Data Models

Key Features Summary

# 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")

Error Handling

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.