azure-data-tables-py
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAzure Tables SDK for Python
Azure Tables SDK for Python
NoSQL key-value store for structured data (Azure Storage Tables or Cosmos DB Table API).
用于结构化数据的NoSQL键值存储(Azure存储表或Cosmos DB表API)。
Installation
安装
bash
pip install azure-data-tables azure-identitybash
pip install azure-data-tables azure-identityEnvironment Variables
环境变量
bash
undefinedbash
undefinedAzure Storage Tables
Azure Storage Tables
AZURE_STORAGE_ACCOUNT_URL=https://<account>.table.core.windows.net
AZURE_STORAGE_ACCOUNT_URL=https://<account>.table.core.windows.net
Cosmos DB Table API
Cosmos DB Table API
COSMOS_TABLE_ENDPOINT=https://<account>.table.cosmos.azure.com
undefinedCOSMOS_TABLE_ENDPOINT=https://<account>.table.cosmos.azure.com
undefinedAuthentication
身份验证
python
from azure.identity import DefaultAzureCredential
from azure.data.tables import TableServiceClient, TableClient
credential = DefaultAzureCredential()
endpoint = "https://<account>.table.core.windows.net"python
from azure.identity import DefaultAzureCredential
from azure.data.tables import TableServiceClient, TableClient
credential = DefaultAzureCredential()
endpoint = "https://<account>.table.core.windows.net"Service client (manage tables)
Service client (管理表)
service_client = TableServiceClient(endpoint=endpoint, credential=credential)
service_client = TableServiceClient(endpoint=endpoint, credential=credential)
Table client (work with entities)
Table client (操作实体)
table_client = TableClient(endpoint=endpoint, table_name="mytable", credential=credential)
undefinedtable_client = TableClient(endpoint=endpoint, table_name="mytable", credential=credential)
undefinedClient Types
客户端类型
| Client | Purpose |
|---|---|
| Create/delete tables, list tables |
| Entity CRUD, queries |
| 客户端 | 用途 |
|---|---|
| 创建/删除表、列出表 |
| 实体CRUD、查询 |
Table Operations
表操作
python
undefinedpython
undefinedCreate table
创建表
service_client.create_table("mytable")
service_client.create_table("mytable")
Create if not exists
不存在则创建
service_client.create_table_if_not_exists("mytable")
service_client.create_table_if_not_exists("mytable")
Delete table
删除表
service_client.delete_table("mytable")
service_client.delete_table("mytable")
List tables
列出表
for table in service_client.list_tables():
print(table.name)
for table in service_client.list_tables():
print(table.name)
Get table client
获取表客户端
table_client = service_client.get_table_client("mytable")
undefinedtable_client = service_client.get_table_client("mytable")
undefinedEntity Operations
实体操作
Important: Every entity requires and (together form unique ID).
PartitionKeyRowKey重要提示:每个实体都需要和(两者共同构成唯一ID)。
PartitionKeyRowKeyCreate Entity
创建实体
python
entity = {
"PartitionKey": "sales",
"RowKey": "order-001",
"product": "Widget",
"quantity": 5,
"price": 9.99,
"shipped": False
}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)
table_client.create_entity(entity=entity)
Upsert (create or replace)
插入或更新(不存在则创建,存在则替换)
table_client.upsert_entity(entity=entity)
undefinedtable_client.upsert_entity(entity=entity)
undefinedGet Entity
获取实体
python
undefinedpython
undefinedGet by key (fastest)
通过键获取(速度最快)
entity = table_client.get_entity(
partition_key="sales",
row_key="order-001"
)
print(f"Product: {entity['product']}")
undefinedentity = table_client.get_entity(
partition_key="sales",
row_key="order-001"
)
print(f"产品: {entity['product']}")
undefinedUpdate Entity
更新实体
python
undefinedpython
undefinedReplace entire entity
替换整个实体
entity["quantity"] = 10
table_client.update_entity(entity=entity, mode="replace")
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")
undefinedupdate = {
"PartitionKey": "sales",
"RowKey": "order-001",
"shipped": True
}
table_client.update_entity(entity=update, mode="merge")
undefinedDelete Entity
删除实体
python
table_client.delete_entity(
partition_key="sales",
row_key="order-001"
)python
table_client.delete_entity(
partition_key="sales",
row_key="order-001"
)Query Entities
查询实体
Query Within Partition
分区内查询
python
undefinedpython
undefinedQuery by partition (efficient)
按分区查询(高效)
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales'"
)
for entity in entities:
print(entity)
undefinedentities = table_client.query_entities(
query_filter="PartitionKey eq 'sales'"
)
for entity in entities:
print(entity)
undefinedQuery with Filters
带筛选条件的查询
python
undefinedpython
undefinedFilter by properties
按属性筛选
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales' and quantity gt 3"
)
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}
)
undefinedentities = table_client.query_entities(
query_filter="PartitionKey eq @pk and price lt @max_price",
parameters={"pk": "sales", "max_price": 50.0}
)
undefinedSelect Specific Properties
选择特定属性
python
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales'",
select=["RowKey", "product", "price"]
)python
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales'",
select=["RowKey", "product", "price"]
)List All Entities
列出所有实体
python
undefinedpython
undefinedList all (cross-partition - use sparingly)
列出所有(跨分区 - 谨慎使用)
for entity in table_client.list_entities():
print(entity)
undefinedfor entity in table_client.list_entities():
print(entity)
undefinedBatch Operations
批量操作
python
from azure.data.tables import TableTransactionErrorpython
from azure.data.tables import TableTransactionErrorBatch 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}")
undefinedoperations = [
("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}")
undefinedAsync Client
异步客户端
python
from azure.data.tables.aio import TableServiceClient, TableClient
from azure.identity.aio import DefaultAzureCredential
async def table_operations():
credential = DefaultAzureCredential()
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())python
from azure.data.tables.aio import TableServiceClient, TableClient
from azure.identity.aio import DefaultAzureCredential
async def table_operations():
credential = DefaultAzureCredential()
async with TableClient(
endpoint="https://<account>.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())Data Types
数据类型
| Python Type | Table Storage Type |
|---|---|
| String |
| Int64 |
| Double |
| Boolean |
| DateTime |
| Binary |
| Guid |
| Python类型 | 表存储类型 |
|---|---|
| String |
| Int64 |
| Double |
| Boolean |
| DateTime |
| Binary |
| Guid |
Best Practices
最佳实践
- Design partition keys for query patterns and even distribution
- Query within partitions whenever possible (cross-partition is expensive)
- Use batch operations for multiple entities in same partition
- Use for idempotent writes
upsert_entity - Use parameterized queries to prevent injection
- Keep entities small — max 1MB per entity
- Use async client for high-throughput scenarios
- 设计分区键以适配查询模式并实现均匀分布
- 尽可能在分区内查询(跨分区查询成本高)
- 使用批量操作处理同一分区内的多个实体
- **使用**实现幂等写入
upsert_entity - 使用参数化查询防止注入
- 保持实体小巧 — 每个实体最大1MB
- 使用异步客户端处理高吞吐量场景