CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-storage-file-share

Azure File Share storage client library for Python

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

service-client.mddocs/

ShareServiceClient - Account-Level Operations

The ShareServiceClient is the entry point for managing Azure File Share operations at the storage account level. It provides methods to configure service properties, manage shares, and obtain clients for specific shares.

Import and Initialization

from azure.storage.fileshare import ShareServiceClient
from azure.core.credentials import AzureNamedKeyCredential
from typing import Optional, Union, Dict, Any, List

Constructor

class ShareServiceClient:
    def __init__(
        self,
        account_url: str,
        credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None,
        *,
        token_intent: Optional[Literal['backup']] = None,
        **kwargs: Any
    ) -> None:
        """
        Create a ShareServiceClient from account URL and credentials.
        
        Parameters:
            account_url: The URL to the file service endpoint
            credential: Authentication credential (key, SAS token, or Azure credential)
            token_intent: Specifies the intent for all requests when using TokenCredential authentication
            **kwargs: Additional client configuration options
        """

Class Methods

@classmethod
def from_connection_string(
    cls,
    conn_str: str,
    credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None,
    **kwargs: Any
) -> ShareServiceClient:
    """
    Create ShareServiceClient from connection string.
    
    Parameters:
        conn_str: Azure Storage connection string
        credential: Optional credential to override connection string auth
        **kwargs: Additional client configuration options
        
    Returns:
        ShareServiceClient: Configured service client instance
    """

Service Properties Management

def get_service_properties(
    self,
    **kwargs: Any
) -> Dict[str, Any]:
    """
    Gets the properties of a storage account's File Share service.
    
    Parameters:
        timeout: Request timeout in seconds
        
    Returns:
        Dict containing service properties including:
        - hour_metrics: Metrics configuration for hourly stats
        - minute_metrics: Metrics configuration for minute stats  
        - cors: List of CORS rules
        - protocol: Protocol settings (SMB settings)
    """

def set_service_properties(
    self,
    hour_metrics: Optional[Metrics] = None,
    minute_metrics: Optional[Metrics] = None, 
    cors: Optional[List[CorsRule]] = None,
    protocol: Optional[ShareProtocolSettings] = None,
    **kwargs: Any
) -> None:
    """
    Sets the properties of a storage account's File Share service.
    
    Parameters:
        hour_metrics: Metrics configuration for hourly aggregated statistics
        minute_metrics: Metrics configuration for minute aggregated statistics
        cors: Cross-origin resource sharing rules
        protocol: Protocol-specific settings (SMB configuration)
        timeout: Request timeout in seconds
    """

Share Management

def list_shares(
    self,
    name_starts_with: Optional[str] = None,
    include_metadata: Optional[bool] = False,
    include_snapshots: Optional[bool] = False,
    **kwargs: Any
) -> ItemPaged[ShareProperties]:
    """
    Returns an auto-paging iterable of ShareProperties under the account.
    
    Parameters:
        name_starts_with: Filter shares by name prefix
        include_metadata: Include share metadata in results
        include_snapshots: Include share snapshots in results
        results_per_page: Number of shares per page
        timeout: Request timeout in seconds
        
    Returns:
        ItemPaged[ShareProperties]: Paginated list of share properties
    """

def create_share(
    self,
    share_name: str,
    **kwargs: Any
) -> ShareClient:
    """
    Creates a new share under the specified account.
    
    Parameters:
        share_name: Name of the share to create
        metadata: Optional dict of name-value pairs for share metadata
        quota: Share size quota in GB (1-102400 for standard, 100-102400 for premium)
        access_tier: Access tier for the share ("Hot", "Cool", "TransactionOptimized", "Premium")
        protocols: Enabled protocols ("SMB", "NFS", or both)
        root_squash: Root squash setting for NFS ("NoRootSquash", "RootSquash", "AllSquash")
        timeout: Request timeout in seconds
        
    Returns:
        ShareClient: Client for the newly created share
    """

def delete_share(
    self,
    share_name: Union[ShareProperties, str],
    delete_snapshots: Optional[bool] = False,
    **kwargs: Any  
) -> None:
    """
    Marks the specified share for deletion.
    
    Parameters:
        share_name: Share to delete (name or ShareProperties object)
        delete_snapshots: Whether to delete share snapshots
        timeout: Request timeout in seconds
    """

def undelete_share(
    self,
    deleted_share_name: str,
    deleted_share_version: str,
    **kwargs: Any
) -> ShareClient:
    """
    Restores soft-deleted share.
    
    Parameters:
        deleted_share_name: Name of the deleted share
        deleted_share_version: Version of the deleted share to restore
        timeout: Request timeout in seconds
        
    Returns:
        ShareClient: Client for the restored share
    """

Client Factory Methods

def get_share_client(
    self,
    share: Union[ShareProperties, str],
    snapshot: Optional[Union[Dict[str, Any], str]] = None
) -> ShareClient:
    """
    Get a client to interact with the specified share.
    
    Parameters:
        share: Share name or ShareProperties object
        snapshot: Optional snapshot identifier
        
    Returns:
        ShareClient: Client configured for the specified share
    """

Properties

@property
def url(self) -> str:
    """The full endpoint URL to the file service."""

@property  
def account_name(self) -> str:
    """The storage account name."""

@property
def credential(self) -> Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]:
    """The credential used to authenticate."""

@property
def api_version(self) -> str:
    """The Storage API version being used."""

Usage Examples

Basic Service Client Setup

from azure.storage.fileshare import ShareServiceClient
from azure.core.credentials import AzureNamedKeyCredential

# Method 1: Connection string
service_client = ShareServiceClient.from_connection_string(
    "DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey;EndpointSuffix=core.windows.net"
)

# Method 2: Account URL + credentials  
credential = AzureNamedKeyCredential("myaccount", "mykey")
service_client = ShareServiceClient(
    account_url="https://myaccount.file.core.windows.net",
    credential=credential
)

# Method 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=..."
)

Managing Service Properties

from azure.storage.fileshare import Metrics, CorsRule, ShareProtocolSettings, ShareSmbSettings, SmbMultichannel

# Configure metrics
hour_metrics = Metrics(
    enabled=True,
    include_apis=True,
    retention_policy={"enabled": True, "days": 7}
)

# Configure CORS
cors_rules = [
    CorsRule(
        allowed_origins=["https://mywebsite.com"],
        allowed_methods=["GET", "PUT", "POST"],
        allowed_headers=["x-ms-*"],
        exposed_headers=["x-ms-*"],
        max_age_in_seconds=3600
    )
]

# Configure SMB protocol settings
smb_settings = ShareSmbSettings(
    multichannel=SmbMultichannel(enabled=True)
)
protocol_settings = ShareProtocolSettings(smb=smb_settings)

# Set service properties
service_client.set_service_properties(
    hour_metrics=hour_metrics,
    cors=cors_rules,
    protocol=protocol_settings
)

# Get current properties
properties = service_client.get_service_properties()
print(f"Hour metrics enabled: {properties['hour_metrics']['enabled']}")
print(f"CORS rules: {len(properties['cors'])}")

Share Lifecycle Management

from azure.storage.fileshare import ShareProtocols

# Create a standard share with 100GB quota
share_client = service_client.create_share(
    share_name="documents",
    quota=100,
    metadata={"environment": "production", "department": "finance"}
)

# Create a premium share with higher performance
premium_share = service_client.create_share(
    share_name="high-performance",
    quota=100,
    access_tier="Premium",
    protocols=[ShareProtocols.SMB]
)

# Create NFS share (requires premium account)
nfs_share = service_client.create_share(
    share_name="nfs-share", 
    protocols=[ShareProtocols.NFS],
    root_squash="NoRootSquash"
)

# List all shares with metadata
shares = list(service_client.list_shares(include_metadata=True, include_snapshots=True))
for share_props in shares:
    print(f"Share: {share_props.name}")
    print(f"  Quota: {share_props.quota} GB")
    print(f"  Access Tier: {share_props.access_tier}")
    print(f"  Metadata: {share_props.metadata}")
    if share_props.snapshot:
        print(f"  Snapshot: {share_props.snapshot}")

# Delete a share and its snapshots
service_client.delete_share("old-share", delete_snapshots=True)

Advanced Share Operations

# List shares with filtering
production_shares = list(service_client.list_shares(name_starts_with="prod-"))

# Restore a soft-deleted share
try:
    restored_share = service_client.undelete_share("deleted-share", "version-id")
    print(f"Restored share: {restored_share.share_name}")
except Exception as e:
    print(f"Could not restore share: {e}")

# Get share client for further operations
share_client = service_client.get_share_client("documents")
snapshot_client = service_client.get_share_client("documents", snapshot="2023-01-01T00:00:00Z")

Error Handling

from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError, HttpResponseError

try:
    # Attempt to create share
    share_client = service_client.create_share("myshare")
except ResourceExistsError:
    # Share already exists, get existing client
    share_client = service_client.get_share_client("myshare")
except HttpResponseError as e:
    if e.error_code == "ShareQuotaExceeded":
        print("Account share limit exceeded")
    else:
        print(f"Failed to create share: {e.message}")

try:
    # Attempt to delete share
    service_client.delete_share("nonexistent-share")
except ResourceNotFoundError:
    print("Share not found for deletion")

Configuration Options

# Service client with custom configuration
service_client = ShareServiceClient.from_connection_string(
    conn_str,
    connection_timeout=30,        # Connection timeout in seconds
    read_timeout=60,             # Read timeout in seconds
    max_range_size=4*1024*1024,  # 4MB range size for operations
    max_single_put_size=64*1024*1024,  # 64MB max single upload
    retry_total=3,               # Number of retry attempts
    retry_backoff_factor=0.4,    # Exponential backoff factor
    transport=transport          # Custom HTTP transport
)

The ShareServiceClient provides comprehensive account-level management capabilities for Azure File Shares. Use it as the entry point to create and manage shares, configure service-wide settings, and obtain clients for specific share operations.

Install with Tessl CLI

npx tessl i tessl/pypi-azure-storage-file-share

docs

async-clients.md

directory-client.md

file-client.md

index.md

lease-client.md

models.md

sas-generation.md

service-client.md

share-client.md

tile.json