azure-cosmos-db-py
microsoft/skills
使用 Python/FastAPI 构建生产级 Azure Cosmos DB NoSQL 服务,内容涵盖支持双重身份验证的客户端配置、服务层的 CRUD 操作、分区键策略、参数化查询以及 TDD 模式。
...展开全部Cosmos DB 服务实现
遵循“干净代码”规范、安全最佳实践和测试驱动开发(TDD)原则,构建生产级 Azure Cosmos DB NoSQL 服务。
安装
pip install azure-cosmos azure-identity
环境变量
COSMOS_ENDPOINT=https://.documents.azure.com:443/ # Required for all auth methods
COSMOS_DATABASE_NAME= # Required for all auth methods
COSMOS_CONTAINER_ID= # Required for all auth methods
# For emulator only (not production)
COSMOS_KEY= # Only required for key-based auth or emulator
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
身份验证与生命周期
🔑 以下每个代码示例均遵循两条规则:
- 优先使用
DefaultAzureCredential。它既可在本地(Azure CLI / VS Code / Developer CLI)使用,也可在Azure中(托管身份、工作负载身份)使用,且无需修改代码。避免使用连接字符串、账户/API密钥——它们会绕过Entra的审计和轮换机制。
- 本地开发:
DefaultAzureCredential可直接使用。- 生产环境:设置
AZURE_TOKEN_CREDENTIALS=prod(或AZURE_TOKEN_CREDENTIALS=) 以将凭据链限制为生产环境安全的凭据。- 将每个客户端封装在上下文管理器中,以确保 HTTP 传输、套接字和令牌缓存能以可预测的方式释放:
- 同步:
with(...) as client: - 异步:
async with以及(...) as client: async with DefaultAzureCredential() as credential:(摘自azure.identity.aio)代码片段中可能会简化此配置,但生产环境代码应始终遵循这两条规则。
DefaultAzureCredential(推荐):
import os
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=
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()
with CosmosClient(
url=os.environ["COSMOS_ENDPOINT"],
credential=credential
) as client:
# Use client here (see following sections for operations)
...
模拟器(本地开发):
from azure.cosmos import CosmosClient
with CosmosClient(
url="https://localhost:8081",
credential=os.environ["COSMOS_KEY"],
connection_verify=False
) as client:
# Use client here (see following sections for operations)
...
架构概述
┌─────────────────────────────────────────────────────────────────┐
│ FastAPI Router │
│ - Auth dependencies (get_current_user, get_current_user_required)
│ - HTTP error responses (HTTPException) │
└──────────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────────┐
│ Service Layer │
│ - Business logic and validation │
│ - Document ↔ Model conversion │
│ - Graceful degradation when Cosmos unavailable │
└──────────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────────┐
│ Cosmos DB Client Module │
│ - Singleton container initialization │
│ - Dual auth: DefaultAzureCredential (Azure) / Key (emulator) │
│ - Async wrapper via run_in_threadpool │
└─────────────────────────────────────────────────────────────────┘
快速入门
1. 客户端模块配置
创建一个支持双重身份验证的 Cosmos 单例客户端:
# db/cosmos.py
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential
from starlette.concurrency import run_in_threadpool
_cosmos_container = None
def _is_emulator_endpoint(endpoint: str) -> bool:
return "localhost" in endpoint or "127.0.0.1" in endpoint
async def get_container():
global _cosmos_container
if _cosmos_container is None:
# Singleton: client lives for the FastAPI app lifetime; close in a lifespan shutdown handler.
if _is_emulator_endpoint(settings.cosmos_endpoint):
client = CosmosClient(
url=settings.cosmos_endpoint,
credential=settings.cosmos_key,
connection_verify=False
)
else:
client = CosmosClient(
url=settings.cosmos_endpoint,
credential=DefaultAzureCredential()
)
db = client.get_database_client(settings.cosmos_database_name)
_cosmos_container = db.get_container_client(settings.cosmos_container_id)
return _cosmos_container
完整实现:参见 references/client-setup.md
2. Pydantic 模型层次结构
采用五层模型模式实现清晰的分离:
class ProjectBase(BaseModel): # Shared fields
name: str = Field(..., min_length=1, max_length=200)
class ProjectCreate(ProjectBase): # Creation request
workspace_id: str = Field(..., alias="workspaceId")
class ProjectUpdate(BaseModel): # Partial updates (all optional)
name: Optional[str] = Field(None, min_length=1)
class Project(ProjectBase): # API response
id: str
created_at: datetime = Field(..., alias="createdAt")
class ProjectInDB(Project): # Internal with docType
doc_type: str = "project"
3. 服务层模式
class ProjectService:
def _use_cosmos(self) -> bool:
return get_container() is not None
async def get_by_id(self, project_id: str, workspace_id: str) -> Project | None:
if not self._use_cosmos():
return None
doc = await get_document(project_id, partition_key=workspace_id)
if doc is None:
return None
return self._doc_to_model(doc)
完整模式:参见 references/service-layer.md
核心原则
安全要求
- 基于角色的访问控制(RBAC)身份验证:在
DefaultAzureCredentialAzure 中的功能——切勿在代码中存储密钥 - 仅限模拟器的密钥:仅在本地开发时将已知的模拟器密钥硬编码
- 参数化查询:始终使用
@parameter语法——切勿使用字符串拼接 - 分区键验证:验证分区键访问是否与用户授权一致
干净代码规范
- 单一职责:客户端模块负责连接;服务负责业务逻辑
- 优雅降级:当
None/[]当 Cosmos 不可用时 - 命名一致性:
_doc_to_model(),_model_to_doc(),_use_cosmos() - 类型提示:所有公共方法均采用完整类型声明
- 驼峰式别名:使用
Field(alias="camelCase")用于 JSON 序列化
TDD 要求
在实现之前,请按照以下模式编写测试:
@pytest.fixture
def mock_cosmos_container(mocker):
container = mocker.MagicMock()
mocker.patch("app.db.cosmos.get_container", return_value=container)
return container
@pytest.mark.asyncio
async def test_get_project_by_id_returns_project(mock_cosmos_container):
# Arrange
mock_cosmos_container.read_item.return_value = {"id": "123", "name": "Test"}
# Act
result = await project_service.get_by_id("123", "workspace-1")
# Assert
assert result.id == "123"
assert result.name == "Test"
完整测试指南:参见 references/testing.md
最佳实践
- 本技能全程使用异步模式(
azure.cosmos.aio);请勿与同步的azure.cosmos客户端混合使用。请确保整个 FastAPI 请求路径均为异步——不要将同步的 Cosmos 调用与异步处理程序配对使用。 - 始终为客户端和异步凭据使用上下文管理器。将客户端封装在
async with CosmosClient(...) as client:(或通过 FastAPI 生命周期管理其生命周期,并显式关闭它)。对于异步DefaultAzureCredential来自azure.identity.aio,还应使用async with credential:,以便清理令牌和传输通道。
参考文件
| 文件 | 何时阅读 |
|---|---|
| references/client-setup.md | 配置支持双重认证、SSL 配置和单例模式的 Cosmos 客户端 |
| references/service-layer.md | 实现包含 CRUD 操作、数据转换和优雅降级的完整服务类 |
| references/testing.md | 编写 pytest 测试、模拟 Cosmos、集成测试设置 |
| references/partitioning.md | 选择分区键、跨分区查询、移动操作 |
| references/error-handling.md | 处理 CosmosResourceNotFoundError、日志记录、HTTP 错误映射 |
模板文件
| 文件 | 用途 |
|---|---|
| assets/cosmos_client_template.py | 即用型客户端模块 |
| assets/service_template.py | 服务类骨架 |
| assets/conftest_template.py | 用于 Cosmos 模拟的 pytest 测试 fixture |
质量属性(NFRs)
可靠性
- 当 Cosmos 不可用时的优雅降级
- 针对瞬态故障采用指数退避的重试逻辑
- 通过单例模式实现连接池
安全性
- 代码中不包含任何密钥(通过 DefaultAzureCredential 实现 RBAC)
- 参数化查询防止注入攻击
- 分区键隔离确保数据边界
可维护性
- 五层模型模式支持模式演进
- 服务层将业务逻辑与存储解耦
- 所有实体服务采用一致的模式
可测试性
- 通过以下方式实现依赖注入
get_container() - 借助模块级全局变量轻松进行模拟
- 清晰的分离使得无需 Cosmos 即可进行单元测试
性能
- 分区键查询可避免跨分区扫描
- 异步封装可防止阻塞 FastAPI 事件循环
- 文档转换开销最小
---
name: azure-cosmos-db-py
description: Build production-grade Azure Cosmos DB NoSQL services with Python/FastAPI, including client setup with dual authentication, service layer CRUD operations, partition key strategies, parameterized queries, and TDD patterns.
license: MIT
---
# Cosmos DB Service Implementation
Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.
## Installation
```bash
pip install azure-cosmos azure-identity
```
## Environment Variables
```bash
COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/ # Required for all auth methods
COSMOS_DATABASE_NAME=<database-name> # Required for all auth methods
COSMOS_CONTAINER_ID=<container-id> # Required for all auth methods
# For emulator only (not production)
COSMOS_KEY=<emulator-key> # Only required for key-based auth or emulator
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.
**DefaultAzureCredential (preferred)**:
```python
import os
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
# 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()
with CosmosClient(
url=os.environ["COSMOS_ENDPOINT"],
credential=credential
) as client:
# Use client here (see following sections for operations)
...
```
**Emulator (local development)**:
```python
from azure.cosmos import CosmosClient
with CosmosClient(
url="https://localhost:8081",
credential=os.environ["COSMOS_KEY"],
connection_verify=False
) as client:
# Use client here (see following sections for operations)
...
```
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────────┐
│ FastAPI Router │
│ - Auth dependencies (get_current_user, get_current_user_required)
│ - HTTP error responses (HTTPException) │
└──────────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────────┐
│ Service Layer │
│ - Business logic and validation │
│ - Document ↔ Model conversion │
│ - Graceful degradation when Cosmos unavailable │
└──────────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────────┐
│ Cosmos DB Client Module │
│ - Singleton container initialization │
│ - Dual auth: DefaultAzureCredential (Azure) / Key (emulator) │
│ - Async wrapper via run_in_threadpool │
└─────────────────────────────────────────────────────────────────┘
```
## Quick Start
### 1. Client Module Setup
Create a singleton Cosmos client with dual authentication:
```python
# db/cosmos.py
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential
from starlette.concurrency import run_in_threadpool
_cosmos_container = None
def _is_emulator_endpoint(endpoint: str) -> bool:
return "localhost" in endpoint or "127.0.0.1" in endpoint
async def get_container():
global _cosmos_container
if _cosmos_container is None:
# Singleton: client lives for the FastAPI app lifetime; close in a lifespan shutdown handler.
if _is_emulator_endpoint(settings.cosmos_endpoint):
client = CosmosClient(
url=settings.cosmos_endpoint,
credential=settings.cosmos_key,
connection_verify=False
)
else:
client = CosmosClient(
url=settings.cosmos_endpoint,
credential=DefaultAzureCredential()
)
db = client.get_database_client(settings.cosmos_database_name)
_cosmos_container = db.get_container_client(settings.cosmos_container_id)
return _cosmos_container
```
**Full implementation**: See [references/client-setup.md](references/client-setup.md)
### 2. Pydantic Model Hierarchy
Use five-tier model pattern for clean separation:
```python
class ProjectBase(BaseModel): # Shared fields
name: str = Field(..., min_length=1, max_length=200)
class ProjectCreate(ProjectBase): # Creation request
workspace_id: str = Field(..., alias="workspaceId")
class ProjectUpdate(BaseModel): # Partial updates (all optional)
name: Optional[str] = Field(None, min_length=1)
class Project(ProjectBase): # API response
id: str
created_at: datetime = Field(..., alias="createdAt")
class ProjectInDB(Project): # Internal with docType
doc_type: str = "project"
```
### 3. Service Layer Pattern
```python
class ProjectService:
def _use_cosmos(self) -> bool:
return get_container() is not None
async def get_by_id(self, project_id: str, workspace_id: str) -> Project | None:
if not self._use_cosmos():
return None
doc = await get_document(project_id, partition_key=workspace_id)
if doc is None:
return None
return self._doc_to_model(doc)
```
**Full patterns**: See [references/service-layer.md](references/service-layer.md)
## Core Principles
### Security Requirements
1. **RBAC Authentication**: Use `DefaultAzureCredential` in Azure — never store keys in code
2. **Emulator-Only Keys**: Hardcode the well-known emulator key only for local development
3. **Parameterized Queries**: Always use `@parameter` syntax — never string concatenation
4. **Partition Key Validation**: Validate partition key access matches user authorization
### Clean Code Conventions
1. **Single Responsibility**: Client module handles connection; services handle business logic
2. **Graceful Degradation**: Services return `None`/`[]` when Cosmos unavailable
3. **Consistent Naming**: `_doc_to_model()`, `_model_to_doc()`, `_use_cosmos()`
4. **Type Hints**: Full typing on all public methods
5. **CamelCase Aliases**: Use `Field(alias="camelCase")` for JSON serialization
### TDD Requirements
Write tests BEFORE implementation using these patterns:
```python
@pytest.fixture
def mock_cosmos_container(mocker):
container = mocker.MagicMock()
mocker.patch("app.db.cosmos.get_container", return_value=container)
return container
@pytest.mark.asyncio
async def test_get_project_by_id_returns_project(mock_cosmos_container):
# Arrange
mock_cosmos_container.read_item.return_value = {"id": "123", "name": "Test"}
# Act
result = await project_service.get_by_id("123", "workspace-1")
# Assert
assert result.id == "123"
assert result.name == "Test"
```
**Full testing guide**: See [references/testing.md](references/testing.md)
## Best Practices
1. **This skill uses async throughout (`azure.cosmos.aio`); do not mix with the sync `azure.cosmos` client.** Keep the whole FastAPI request path async — don't pair sync Cosmos calls with async handlers.
2. **Always use context managers for clients and async credentials.** Wrap the client in `async with CosmosClient(...) as client:` (or manage its lifetime via FastAPI lifespan and close it explicitly). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
## Reference Files
| File | When to Read |
|------|--------------|
| [references/client-setup.md](references/client-setup.md) | Setting up Cosmos client with dual auth, SSL config, singleton pattern |
| [references/service-layer.md](references/service-layer.md) | Implementing full service class with CRUD, conversions, graceful degradation |
| [references/testing.md](references/testing.md) | Writing pytest tests, mocking Cosmos, integration test setup |
| [references/partitioning.md](references/partitioning.md) | Choosing partition keys, cross-partition queries, move operations |
| [references/error-handling.md](references/error-handling.md) | Handling CosmosResourceNotFoundError, logging, HTTP error mapping |
## Template Files
| File | Purpose |
|------|---------|
| [assets/cosmos_client_template.py](assets/cosmos_client_template.py) | Ready-to-use client module |
| [assets/service_template.py](assets/service_template.py) | Service class skeleton |
| [assets/conftest_template.py](assets/conftest_template.py) | pytest fixtures for Cosmos mocking |
## Quality Attributes (NFRs)
### Reliability
- Graceful degradation when Cosmos unavailable
- Retry logic with exponential backoff for transient failures
- Connection pooling via singleton pattern
### Security
- Zero secrets in code (RBAC via DefaultAzureCredential)
- Parameterized queries prevent injection
- Partition key isolation enforces data boundaries
### Maintainability
- Five-tier model pattern enables schema evolution
- Service layer decouples business logic from storage
- Consistent patterns across all entity services
### Testability
- Dependency injection via `get_container()`
- Easy mocking with module-level globals
- Clear separation enables unit testing without Cosmos
### Performance
- Partition key queries avoid cross-partition scans
- Async wrapping prevents blocking FastAPI event loop
- Minimal document conversion overhead





首页
