適用於 Python 的 Azure SDK 語言設計指導方針

Azure SDK 語言設計指引是全面的標準,確保所有 Azure SDK 的一致性、可預測性與易用性。 這些指導方針可協助開發人員有效率地使用 Azure 服務,方法是在不同服務和程式設計語言之間提供熟悉的模式和行為。

該指南包括兩類:

  • 一般指引:適用於所有 Azure SDK 的核心原則,不論程式語言為何。
  • Language-Specific 指引:針對各支援語言(包括 Python、 .NET、 Java、 TypeScript 等)優化的實作細節。 欲了解更多資訊,請參閱 一般指引:導言 頁面的目錄。

這些指引在 GitHub 上公開制定,允許社群審查與貢獻。

一般設計原則

所有 Azure SDK 都遵循下列基本原則:

㪄 Description
慣用用法 SDK 遵循語言特定的慣例與模式。
一致性 不同 Azure 服務的行為是一致的。
單純 常見任務只需最少的程式碼。
漸進式披露 雖然有進階功能,但不會讓基本操作變得複雜。
穩健性 系統內建了錯誤處理、重試和超時的功能。

Python 特定指導方針

本文件的其餘部分著重於 Python 的指引。

命名慣例

適用於 Python 的 Azure SDK 遵循標準 Python 命名慣例:

  • 方法:使用 snake_case。

    list_containers()
    get_secret()
    create_database()
    
  • 變數:使用 snake_case。

    connection_string = "..."
    retry_count = 3
    
  • 類別:使用 PascalCase。

    BlobServiceClient
    SecretClient
    CosmosClient
    
  • 常數:使用 UPPER_CASE。

    DEFAULT_CHUNK_SIZE
    MAX_RETRIES
    

封裝結構

Azure SDK 套件遵循一致的結構:

azure-<service>-<feature>
├── azure/
│   └── <service>/
│       ├── __init__.py
│       ├── _client.py
│       ├── _models.py
│       └── aio/           # Async implementations
│           └── __init__.py

用戶端實例化

用戶端提供多種實例化方法:

from azure.storage.blob import BlobServiceClient
from azure.identity import DefaultAzureCredential

# Note: Do not use connection string if you can possibly avoid it!

# Using account URL and credential
credential = DefaultAzureCredential()
client = BlobServiceClient(account_url="https://account.blob.core.windows.net", 
                          credential=credential)

Authentication

Azure SDK 會使用一致的驗證模式:

from azure.identity import DefaultAzureCredential, ClientSecretCredential

# Default credential chain
credential = DefaultAzureCredential()

# Explicit credential
credential = ClientSecretCredential(
    tenant_id="tenant-id",
    client_id="client-id",
    client_secret="secret"
)

內容管理員

大部分的 Azure SDK 用戶端都會實作內容管理員通訊協定,以進行自動資源清除:

from azure.storage.blob import BlobServiceClient

# Automatic cleanup with context manager
with BlobServiceClient.from_connection_string(conn_str) as client:
    container_client = client.get_container_client("mycontainer")
    blob_list = container_client.list_blobs()

備註

雖然大多數客戶端支援上下文管理器,但請確認特定客戶文件是否可用。

非同步作業

非同步用戶端在個別 .aio 模組中提供:

from azure.storage.blob.aio import BlobServiceClient
import asyncio

async def list_blobs_async():
    async with BlobServiceClient.from_connection_string(conn_str) as client:
        container_client = client.get_container_client("mycontainer")
        async for blob in container_client.list_blobs():
            print(blob.name)

# Run async function
asyncio.run(list_blobs_async())

長時間執行的作業

長時間執行的操作會使用 begin_ 作為前綴,並返回輪詢物件:

from azure.storage.blob import BlobServiceClient

client = BlobServiceClient.from_connection_string(conn_str)
container_client = client.get_container_client("mycontainer")

# Start long-running operation
poller = container_client.begin_copy_blob_from_url(source_url)

# Wait for completion
result = poller.result()

# Or check status
if poller.done():
    result = poller.result()

分頁

清單作業會傳回自動處理分頁的可疊代專案:

from azure.storage.blob import BlobServiceClient

client = BlobServiceClient.from_connection_string(conn_str)

# Automatic pagination
for container in client.list_containers():
    print(container.name)

# Manual pagination control
containers = client.list_containers(results_per_page=10).by_page()
for page in containers:
    for container in page:
        print(container.name)

傳回類型

方法會傳回強型別模型物件,而不是字典:

from azure.keyvault.secrets import SecretClient

client = SecretClient(vault_url="...", credential=credential)

# Returns KeyVaultSecret object, not dict
secret = client.get_secret("my-secret")
print(secret.value)
print(secret.properties.created_on)

錯誤處理

Azure SDK 的例外(Exceptions)從 AzureError 繼承而來,並提供具體的例外類型:

from azure.core.exceptions import (
    AzureError,
    ResourceNotFoundError,
    ResourceExistsError,
    ClientAuthenticationError,
    HttpResponseError
)

try:
    blob_client.download_blob()
except ResourceNotFoundError:
    # Handle missing resource
    print("Blob not found")
except ClientAuthenticationError:
    # Handle authentication failure
    print("Authentication failed")
except HttpResponseError as e:
    # Handle HTTP errors
    print(f"HTTP {e.status_code}: {e.message}")
except AzureError as e:
    # Handle any other Azure SDK error
    print(f"Azure SDK error: {e}")

設定選項

用戶端會透過關鍵字引數接受設定:

from azure.storage.blob import BlobServiceClient

client = BlobServiceClient(
    account_url="...",
    credential=credential,
    # Configuration options
    max_single_put_size=64 * 1024 * 1024,
    max_block_size=4 * 1024 * 1024,
    retry_total=3,
    logging_enable=True
)

常見的 SDK 模式

服務用戶端階層

Azure SDK 通常遵循三層階層:

  • 服務客戶:服務營運的入口:

    service_client = BlobServiceClient(...)
    
  • 資源客戶端:對特定資源的操作:

    container_client = service_client.get_container_client("container")
    
  • 操作方法:對資源的行動:

    blob_client = container_client.get_blob_client("blob.txt")
    blob_client.upload_blob(data)
    

一致的方法命名

方法名稱遵循可預測的模式:

行動 方法模式 Example
Create create_<resource> create_container()
參閱 get_<resource> get_blob()
Update update_<resource> update_secret()
刪除 delete_<resource> delete_container()
清單 list_<resources> list_blobs()
Exists exists() blob_client.exists()

使用 Azure SDK 套件

下列範例示範設計指導方針如何在不同的 Azure 服務之間建立一致性:

from azure.storage.blob import BlobServiceClient
from azure.keyvault.secrets import SecretClient
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential

# Consistent authentication
credential = DefaultAzureCredential()

# Consistent client instantiation
blob_service = BlobServiceClient(
    account_url="https://account.blob.core.windows.net",
    credential=credential
)
secret_client = SecretClient(
    vault_url="https://vault.vault.azure.net",
    credential=credential
)
cosmos_client = CosmosClient(
    url="https://account.documents.azure.com",
    credential=credential
)

# Consistent method patterns
containers = blob_service.list_containers()
secrets = secret_client.list_properties_of_secrets()
databases = cosmos_client.list_databases()

# Consistent error handling
from azure.core.exceptions import ResourceNotFoundError

try:
    blob_service.get_container_client("container").get_container_properties()
    secret_client.get_secret("secret")
    cosmos_client.get_database_client("database").read()
except ResourceNotFoundError as e:
    print(f"Resource not found: {e}")

貢獻於 Azure SDKs

當你擴充或貢獻 Azure SDK 時:

  • 遵循 Python 成語: 使用Python的模式和慣例。
  • 保持一致性: 與現有的 SDK 模式保持一致。
  • 撰寫完整的測驗: 包含單元測試與整合測試。
  • 詳細記錄: 提供文件字串和範例。
  • 評論指引: 請參閱 Azure SDK 貢獻指南。

以下是一個依照語言設計指引實作自訂客戶端方法的範例:

def list_items_with_prefix(self, prefix: str, **kwargs) -> ItemPaged[ItemProperties]:
    """List items that start with the specified prefix.
    
    :param str prefix: The prefix to filter items
    :return: An iterable of ItemProperties
    :rtype: ~azure.core.paging.ItemPaged[ItemProperties]
    
    :example:
        items = client.list_items_with_prefix("test-")
        for item in items:
            print(item.name)
    """
    return self.list_items(name_starts_with=prefix, **kwargs)