azure-data-tables-py
microsoft/skills
Azure Storage Tables 또는 Cosmos DB Table API에 대한 NoSQL 키-값 저장, 엔티티 CRUD, 일괄 작업 및 쿼리를 수행하기 위해 Python용 Azure Tables SDK를 사용하는 방법에 대한 코드 예제와 모범 사례를 제공합니다.
...모든 것을 확장하십시오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 / Developer CLI) 및 Azure(관리형 ID, 워크로드 ID)에서 모두 작동합니다. 연결 문자열, 계정/API 키는 사용하지 마십시오. 이러한 방법은 Entra 감사 및 키 순환 기능을 우회합니다.
- 로컬 개발:
DefaultAzureCredential은별다른 설정 없이 바로 작동합니다.- 프로덕션:
AZURE_TOKEN_CREDENTIALS=prod(또는AZURE_TOKEN_CREDENTIALS=)를 설정하여 자격 증명 체인을 프로덕션에 안전한 자격 증명만 사용하도록 제한하십시오.- 모든 클라이언트를 컨텍스트 매니저로 감싸서 HTTP 전송, 소켓 및 토큰 캐시가 결정론적으로 해제되도록 하십시오:
- 동기식:
(...) as client: - 비동기:
및(...)을 클라이언트로 사용하는 async DefaultAzureCredential()을 자격 증명으로 사용하는 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가 필요합니다(이 두 개가 결합되어 고유 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"제품: {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 |
Boolean |
datetime |
DateTime |
바이트 |
바이너리 |
UUID |
GUID |
모범 사례
- 동기식 또는 비동기식 중 하나를 선택하고 일관성을 유지하십시오. 동일한 호출 경로 내에서
azure.data.tables동기식 클라이언트와azure.data.tables.aio비동기식 클라이언트를 혼합하여 사용하지 마십시오. 모듈당 하나의 모드를 선택하십시오. - 클라이언트 및 비동기 자격 증명에는 항상 컨텍스트 관리자를 사용하십시오. 모든 클라이언트를
TableClient(...) as client:(동기) 또는TableClient(...) as client: (비동기)로감싸십시오. 비동기 모드의 경우azure.identity.aio의DefaultAzureCredential을사용할 때도credential:을 사용하여 비동기 모드로설정해야 토큰과 전송 정보가 제대로 정리됩니다. - 로컬 개발 환경과 Azure 간에 이식 가능한 인증을 위해
DefaultAzureCredential을사용하십시오 (가능한 경우 연결 문자열/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
복사





집
