Azure SDK 言語設計ガイドラインは、すべての Azure SDK の一貫性、予測可能性、使いやすさを保証する包括的な標準です。 これらのガイドラインは、開発者がさまざまなサービスとプログラミング言語で使い慣れたパターンと動作を提供することで、Azure サービスを効率的に操作するのに役立ちます。
ガイドラインは、次の 2 つのカテゴリで構成されます。
- 一般的なガイドライン: プログラミング言語に関係なく、すべての 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 の例外は 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 は、通常、次の 3 レベルの階層に従います。
サービス クライアント: サービス操作のエントリ ポイント:
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)
一貫性のあるメソッドの名前付け
メソッド名は、予測可能なパターンに従います。
| Operation | メソッド パターン | Example |
|---|---|---|
| Create | create_<resource> |
create_container() |
| Read | 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 SDK への投稿
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)