azure-data-tables-py
microsoft/skills
提供使用 Azure Tables SDK for Python 進行 NoSQL 鍵值儲存、實體 CRUD 操作、批次操作以及針對 Azure Storage Tables 或 Cosmos DB Table API 執行查詢的程式碼範例與最佳實務。
...展開全部Azure Tables Python 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 時才需設定
驗證與生命週期
🔑 以下每個程式碼範例均適用兩項規則:
- 優先使用
DefaultAzureCredential。它可在本地端(Azure CLI / VS Code / Developer CLI)及 Azure 環境(託管身分識別、工作負載身分識別)中運作,且無需修改程式碼。請避免使用連線字串、帳戶/API 金鑰——這些會繞過 Entra 稽核與輪替機制。
- 本地開發:
DefaultAzureCredential可直接使用。- 生產環境:設定
AZURE_TOKEN_CREDENTIALS=prod(或AZURE_TOKEN_CREDENTIALS=),以將憑證鏈限制為符合生產環境安全標準的憑證。- 將每個客戶端封裝在上下文管理器中,以確保 HTTP 傳輸、套接字和憑證快取能以可預測的方式釋放:
- 同步模式:
使用 ``(...) as client: - 非同步:
使用 ``(...)` 作為 `client` 的 `async ,以及使用 `DefaultAzureCredential()` 作為 `credential` 的 `async`:(來自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(兩者共同構成唯一識別碼)。
建立實體
entity = {
"PartitionKey": "sales",
"RowKey": "order-001",
"product": "Widget",
"quantity": 5,
"price": 9.99,
"shipped": False
}
# 建立(若已存在則失敗)
table_client.create_entity(entity=entity)
# Upsert(建立或替換)
table_client.upsert_entity(entity=entity)
取得實體
# 透過鍵值擷取(最快)
entity = table_client.get_entity(
partition_key="sales",
row_key="order-001"
)
print(f"產品:{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 資料型別 | 表儲存類型 |
|---|---|
str |
字串 |
int |
Int64 |
float |
Double |
bool |
布林值 |
datetime |
DateTime |
位元組 |
二進位 |
UUID |
GUID |
最佳實務
- 請選擇「同步」或「非同步」模式,並保持一致。請勿在同一個呼叫路徑中混合使用
azure.data.tables的同步客戶端與azure.data.tables.aio的非同步客戶端。每個模組應僅採用一種模式。 - 請務必為客戶端和非同步憑證使用上下文管理器。將每個客戶端
以 TableClient(...) as client:(sync)(同步模式)或TableClient(...) as client:(async)(非同步模式)進行封裝。 對於來自azure.identity.aio的非同步DefaultAzureCredential,也請搭配 credential:參數使用非同步模式,以便妥善清理憑證和傳輸資料。 - 請使用
DefaultAzureCredential實現本地開發環境與 Azure 之間的可移植驗證(盡可能避免使用連線字串/API 金鑰)。 - 根據查詢模式設計分區鍵,並確保均勻分佈
- 盡可能在分區內進行查詢(跨分區查詢成本較高)
- 針對同一分區內的多個實體,請使用批次操作
- 使用`
upsert_entity` 進行幺正寫入 - 使用參數化查詢以防止注入攻擊
- 保持實體大小適中— 每個實體最大 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
複製





首頁
