azure-data-tables-py
microsoft/skills
提供了使用 Python 版 Azure Tables SDK 进行 NoSQL 键值存储、实体 CRUD 操作、批处理操作以及对 Azure Storage Tables 或 Cosmos DB Table API 进行查询的代码示例和最佳实践。
...展开全部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 时才需要
身份验证与生命周期
🔑 以下每个代码示例均遵循两条规则:
- 优先使用
DefaultAzureCredential。它既可在本地(Azure CLI / VS Code / 开发者 CLI)使用,也可在 Azure 中(托管身份、工作负载身份)使用,且无需修改代码。避免使用连接字符串、账户/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(二者共同构成唯一标识符)。
创建实体
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
复制





首页
