azure-data-tables-py
microsoft/skills
Azure Tables SDK for Python を使用して、Azure Storage Tables または Cosmos DB Table API に対して NoSQL キーバリュー型ストレージ、エンティティの CRUD 操作、バッチ操作、およびクエリを実行するためのコードサンプルとベストプラクティスを提供します。
...すべて拡張しますPython用 Azure Tables SDK
構造化データ用の NoSQL キーバリューストア(Azure Storage Tables または Cosmos DB Table API)。
インストール
pip install azure-data-tables azure-identity
環境変数
# Azure Storage Tables
AZURE_STORAGE_ACCOUNT_URL=https://.table.core.windows.net # Azure Storage Tables に必要な環境変数
# Cosmos DB Table API
COSMOS_TABLE_ENDPOINT=https://.table.cosmos.azure.com # Cosmos DB Table API に必要
AZURE_TOKEN_CREDENTIALS=prod # 本番環境で DefaultAzureCredential を使用する場合にのみ必要
認証とライフサイクル
🔑 以下のすべてのコードサンプルには、次の 2 つのルールが適用されます:
DefaultAzureCredential を優先してください。コードを変更することなく、ローカル(Azure CLI / VS Code / Developer CLI)および Azure(マネージド ID、ワークロード ID)で動作します。接続文字列やアカウント/API キーの使用は避けてください。これらは Entra の監査およびローテーションの対象外となります。
- ローカル開発:
DefaultAzureCredentialはそのまま使用できます。- 本番環境:
AZURE_TOKEN_CREDENTIALS=prod(またはAZURE_TOKEN_CREDENTIALS=)を設定し、認証情報チェーンを本番環境に適した認証情報に制限してください。- すべてのクライアントをコンテキストマネージャーでラップし、HTTPトランスポート、ソケット、トークンキャッシュが確定的に解放されるようにします:
- 同期:
(...) as client: - 非同期:
`async with` および(...) as client: `async with DefaultAzureCredential() as credential:` (azure.identity.aioより)スニペットではこの設定を省略している場合がありますが、本番環境のコードでは常に両方のルールに従う必要があります。
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.data.tables import TableServiceClient, TableClient
# ローカル開発環境: DefaultAzureCredential。本番環境: AZURE_TOKEN_CREDENTIALS=prod または AZURE_TOKEN_CREDENTIALS=を設定
credential = DefaultAzureCredential(require_envvar=True)
# または、本番環境では特定の認証情報を直接使用することも可能です:
# https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes を参照してください
# credential = ManagedIdentityCredential()
endpoint = "https://.table.core.windows.net"
# サービスクライアント(テーブルの管理)
with TableServiceClient(endpoint=endpoint, credential=credential) as service_client:
# ここで service_client を使用します(操作については後述のセクションを参照)
...
# テーブルクライアント(エンティティの操作)
with TableClient(endpoint=endpoint, table_name="mytable", credential=credential) as table_client:
# ここで table_client を使用します(操作については後述のセクションを参照)
...
クライアントの種類
| クライアント | 目的 |
|---|---|
TableServiceClient |
テーブルの作成・削除、テーブルの一覧取得 |
TableClient |
エンティティのCRUD、クエリ |
テーブル操作
# テーブルの作成
service_client.create_table("mytable")
# 存在しない場合は作成
service_client.create_table_if_not_exists("mytable")
# テーブルの削除
service_client.delete_table("mytable")
# テーブルの一覧表示
for table in service_client.list_tables():
print(table.name)
# テーブルクライアントの取得
table_client = service_client.get_table_client("mytable")
エンティティ操作
重要:すべてのエンティティには、PartitionKeyとRowKey(これらを組み合わせることで一意の ID が形成される)が必要です。
エンティティの作成
entity = {
"PartitionKey": "sales",
"RowKey": "order-001",
"product": "Widget",
"quantity": 5,
"price": 9.99,
"shipped": False
}
# 作成(存在する場合は失敗)
table_client.create_entity(entity=entity)
# アップサート(作成または置換)
table_client.upsert_entity(entity=entity)
エンティティの取得
# キーによる取得(最速)
entity = table_client.get_entity(
partition_key="sales",
row_key="order-001"
)
print(f"Product: {entity['product']}")
エンティティの更新
# エンティティ全体を置換
entity["quantity"] = 10
table_client.update_entity(entity=entity, mode="replace")
# マージ(特定のフィールドのみを更新)
update = {
"PartitionKey": "sales",
"RowKey": "order-001",
"shipped": True
}
table_client.update_entity(entity=update, mode="merge")
エンティティの削除
table_client.delete_entity(
partition_key="sales",
row_key="order-001"
)
エンティティのクエリ
パーティション内でのクエリ
# パーティション単位でのクエリ(効率的)
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales'"
)
for entity in entities:
print(entity)
フィルタを用いたクエリ
# プロパティによるフィルタリング
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales' and quantity gt 3"
)
# パラメータ指定 (より安全)
entities = table_client.query_entities(
query_filter="PartitionKey eq @pk and price lt @max_price",
parameters={"pk": "sales", "max_price": 50.0}
)
特定のプロパティの選択
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales'",
select=["RowKey", "product", "price"]
)
すべてのエンティティの一覧表示
# すべてを一覧表示(パーティションをまたぐため、使用は控えめに)
for entity in table_client.list_entities():
print(entity)
バッチ操作
from azure.data.tables import TableTransactionError
# バッチ操作(同一パーティションのみ!)
operations = [
("create", {"PartitionKey": "batch", "RowKey": "1", "data": "first"}),
("create", {"PartitionKey": "batch", "RowKey": "2", "data": "second"}),
("upsert", {"PartitionKey": "batch", "RowKey": "3", "data": "third"}),
]
try:
table_client.submit_transaction(operations)
except TableTransactionError as e:
print(f"トランザクションが失敗しました: {e}")
非同期クライアント
from azure.data.tables.aio import TableServiceClient, TableClient
from azure.identity.aio import DefaultAzureCredential
async def table_operations():
async with DefaultAzureCredential() as credential:
async with TableClient(
endpoint="https://.table.core.windows.net",
table_name="mytable",
credential=credential
) as client:
# 作成
await client.create_entity(entity={
"PartitionKey": "async",
"RowKey": "1",
"data": "test"
})
# クエリ
async for entity in client.query_entities("PartitionKey eq 'async'"):
print(entity)
import asyncio
asyncio.run(table_operations())
データ型
| Pythonの型 | Table Storage 型 |
|---|---|
str |
文字列 |
int |
Int64 |
float |
Double |
bool |
Boolean |
datetime |
DateTime |
バイト |
バイナリ |
UUID |
GUID |
ベストプラクティス
- 同期か非同期のいずれかを選択し、一貫性を保ってください。同じ呼び出しパス内で、
azure.data.tablesの同期クライアントとazure.data.tables.aioの非同期クライアントを混在させないでください。モジュールごとに 1 つのモードを選択してください。 - クライアントおよび非同期の認証情報には、常にコンテキストマネージャーを使用してください。すべてのクライアントを
、TableClient(...) as client:(sync) またはTableClient(...) as client:(async)でラップしてください。 非同期の場合、azure.identity.aioのDefaultAzureCredentialを使用する際は、credential: とともに非同期モードも使用し、トークンとトランスポートが適切にクリーンアップされるようにしてください。 - ローカル開発環境とAzureをまたぐポータブルな認証には、
`DefaultAzureCredential`を使用してください(可能な限り、接続文字列やAPIキーの使用は避けてください)。 - クエリパターンと均等な分散を考慮してパーティションキーを設計してください
- 可能な限りパーティション内でクエリを実行してください(パーティション間のクエリはコストがかかります)
- 同じパーティション内の複数のエンティティに対しては、バッチ操作を使用してください
- 冪等な書き込みには `
upsert_entity`を使用してください - インジェクションを防ぐために、パラメータ化されたクエリを使用する
- エンティティのサイズを小さく保つ— 1エンティティあたり最大1MB
- 高スループットが必要なシナリオでは、非同期クライアントを使用する
---
name: azure-data-tables-py
description: Provides code samples and best practices for using the Azure Tables SDK for Python to perform NoSQL key-value storage, entity CRUD, batch operations, and queries against Azure Storage Tables or Cosmos DB Table API.
license: MIT
---
# Azure Tables SDK for Python
NoSQL key-value store for structured data (Azure Storage Tables or Cosmos DB Table API).
## Installation
```bash
pip install azure-data-tables azure-identity
```
## Environment Variables
```bash
# Azure Storage Tables
AZURE_STORAGE_ACCOUNT_URL=https://<account>.table.core.windows.net # Required for Azure Storage Tables
# Cosmos DB Table API
COSMOS_TABLE_ENDPOINT=https://<account>.table.cosmos.azure.com # Required for Cosmos DB Table API
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication & Lifecycle
> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
> - Local dev: `DefaultAzureCredential` works as-is.
> - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
> - Sync: `with <Client>(...) as client:`
> - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.
```python
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.data.tables import TableServiceClient, TableClient
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
endpoint = "https://<account>.table.core.windows.net"
# Service client (manage tables)
with TableServiceClient(endpoint=endpoint, credential=credential) as service_client:
# Use service_client here (see following sections for operations)
...
# Table client (work with entities)
with TableClient(endpoint=endpoint, table_name="mytable", credential=credential) as table_client:
# Use table_client here (see following sections for operations)
...
```
## Client Types
| Client | Purpose |
|--------|---------|
| `TableServiceClient` | Create/delete tables, list tables |
| `TableClient` | Entity CRUD, queries |
## Table Operations
```python
# Create table
service_client.create_table("mytable")
# Create if not exists
service_client.create_table_if_not_exists("mytable")
# Delete table
service_client.delete_table("mytable")
# List tables
for table in service_client.list_tables():
print(table.name)
# Get table client
table_client = service_client.get_table_client("mytable")
```
## Entity Operations
**Important**: Every entity requires `PartitionKey` and `RowKey` (together form unique ID).
### Create Entity
```python
entity = {
"PartitionKey": "sales",
"RowKey": "order-001",
"product": "Widget",
"quantity": 5,
"price": 9.99,
"shipped": False
}
# Create (fails if exists)
table_client.create_entity(entity=entity)
# Upsert (create or replace)
table_client.upsert_entity(entity=entity)
```
### Get Entity
```python
# Get by key (fastest)
entity = table_client.get_entity(
partition_key="sales",
row_key="order-001"
)
print(f"Product: {entity['product']}")
```
### Update Entity
```python
# Replace entire entity
entity["quantity"] = 10
table_client.update_entity(entity=entity, mode="replace")
# Merge (update specific fields only)
update = {
"PartitionKey": "sales",
"RowKey": "order-001",
"shipped": True
}
table_client.update_entity(entity=update, mode="merge")
```
### Delete Entity
```python
table_client.delete_entity(
partition_key="sales",
row_key="order-001"
)
```
## Query Entities
### Query Within Partition
```python
# Query by partition (efficient)
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales'"
)
for entity in entities:
print(entity)
```
### Query with Filters
```python
# Filter by properties
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales' and quantity gt 3"
)
# With parameters (safer)
entities = table_client.query_entities(
query_filter="PartitionKey eq @pk and price lt @max_price",
parameters={"pk": "sales", "max_price": 50.0}
)
```
### Select Specific Properties
```python
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales'",
select=["RowKey", "product", "price"]
)
```
### List All Entities
```python
# List all (cross-partition - use sparingly)
for entity in table_client.list_entities():
print(entity)
```
## Batch Operations
```python
from azure.data.tables import TableTransactionError
# Batch operations (same partition only!)
operations = [
("create", {"PartitionKey": "batch", "RowKey": "1", "data": "first"}),
("create", {"PartitionKey": "batch", "RowKey": "2", "data": "second"}),
("upsert", {"PartitionKey": "batch", "RowKey": "3", "data": "third"}),
]
try:
table_client.submit_transaction(operations)
except TableTransactionError as e:
print(f"Transaction failed: {e}")
```
## Async Client
```python
from azure.data.tables.aio import TableServiceClient, TableClient
from azure.identity.aio import DefaultAzureCredential
async def table_operations():
async with DefaultAzureCredential() as credential:
async with TableClient(
endpoint="https://<account>.table.core.windows.net",
table_name="mytable",
credential=credential
) as client:
# Create
await client.create_entity(entity={
"PartitionKey": "async",
"RowKey": "1",
"data": "test"
})
# Query
async for entity in client.query_entities("PartitionKey eq 'async'"):
print(entity)
import asyncio
asyncio.run(table_operations())
```
## Data Types
| Python Type | Table Storage Type |
|-------------|-------------------|
| `str` | String |
| `int` | Int64 |
| `float` | Double |
| `bool` | Boolean |
| `datetime` | DateTime |
| `bytes` | Binary |
| `UUID` | Guid |
## Best Practices
1. **Pick sync OR async and stay consistent.** Do not mix `azure.data.tables` sync clients with `azure.data.tables.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with TableClient(...) as client:` (sync) or `async with TableClient(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use `DefaultAzureCredential`** for portable auth across local dev and Azure (avoid connection strings / API keys when possible).
4. **Design partition keys** for query patterns and even distribution
5. **Query within partitions** whenever possible (cross-partition is expensive)
6. **Use batch operations** for multiple entities in same partition
7. **Use `upsert_entity`** for idempotent writes
8. **Use parameterized queries** to prevent injection
9. **Keep entities small** — max 1MB per entity
10. **Use async client** for high-throughput scenarios
すべてのファイル
0件のファイルazure-data-tables-pyをインストール
スキルファイルをダウンロードし、.claude/skills/ ディレクトリに解凍してください。
ZIPをダウンロードリポジトリをクローンし、スキルファイルをプロジェクトにコピーしてください。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-data-tables-py # Copy SKILL.md to your .claude/skills/ directory
コピー





家
