azure-cosmos-py
microsoft/skills
Выполняйте операции CRUD, запускайте запросы и управляйте контейнерами в Azure Cosmos DB NoSQL API с помощью SDK для Python.
...Расширить всеSDK Azure Cosmos DB для Python
Клиентская библиотека для NoSQL-API Azure Cosmos DB — глобально распределенной мультимодельной базы данных.
Установка
pip install azure-cosmos azure-identity
Переменные среды
COSMOS_ENDPOINT=https://.documents.azure.com:443/ # Требуется для всех методов аутентификации
COSMOS_DATABASE=mydb # Требуется для всех методов аутентификации
COSMOS_CONTAINER=mycontainer # Требуется для всех методов аутентификации
AZURE_TOKEN_CREDENTIALS=prod # Требуется только в том случае, если в производственной среде используется DefaultAzureCredential
Аутентификация и жизненный цикл
🔑 К каждому приведённому ниже примеру кода применяются два правила:
- Предпочтительно использовать
DefaultAzureCredential. Он работает как локально (Azure CLI / VS Code / Developer CLI), так и в Azure (управляемая идентичность, идентичность рабочей нагрузки) без изменения кода. Избегайте использования строк подключения, учетных записей и ключей API — они обходят аудит и ротацию Entra.
- Локальная разработка:
DefaultAzureCredentialработает без изменений.- Производственная среда: установите
AZURE_TOKEN_CREDENTIALS=prod(илиAZURE_TOKEN_CREDENTIALS=), чтобы ограничить цепочку учетных данных учетными данными, безопасными для производственной среды.- Оберните каждый клиент в менеджер контекста, чтобы HTTP-транспорт, сокеты и кэши токенов освобождались детерминированно:
- Синхронный режим:
с(...) в качестве клиента: - Асинхронный режим:
async си(...) в качестве клиента: async с DefaultAzureCredential() в качестве учетных данных:(изazure.identity.aio)В фрагментах кода эту настройку можно сократить, но в производственном коде всегда следует соблюдать оба правила.
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.cosmos import CosmosClient
# Локальная разработка: 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://.documents.azure.com:443/"
with CosmosClient(url=endpoint, credential=credential) as client:
# Используйте клиент здесь (операции см. в следующих разделах)
...
Иерархия клиентов
| Клиент | Назначение | Получить из |
|---|---|---|
CosmosClient |
Операции на уровне учетной записи | Прямое создание экземпляра |
DatabaseProxy |
Операции с базой данных | client.get_database_client() |
ContainerProxy |
Операции с контейнером/элементом | database.get_container_client() |
Основной рабочий процесс
Настройка базы данных и контейнера
# Получить или создать базу данных
database = client.create_database_if_not_exists(id="mydb")
# Получить или создать контейнер с ключом разбиения
container = database.create_container_if_not_exists(
id="mycontainer",
partition_key=PartitionKey(path="/category")
)
# Получить существующие объекты
database = client.get_database_client("mydb")
container = database.get_container_client("mycontainer")
Создать элемент
item = {
"id": "item-001", # Обязательно: уникально внутри раздела
"category": "electronics", # Значение ключа раздела
"name": "Laptop",
"price": 999.99,
"tags": ["computer", "portable"]
}
created = container.create_item(body=item)
print(f"Создано: {created['id']}")
Чтение элемента
# Для чтения требуется id И ключ раздела
item = container.read_item(
item="item-001",
partition_key="electronics"
)
print(f"Название: {item['name']}")
Обновление элемента (замена)
item = container.read_item(item="item-001", partition_key="electronics")
item["price"] = 899.99
item["on_sale"] = True
updated = container.replace_item(item=item["id"], body=item)
Добавление или обновление элемента
# Создать, если не существует, заменить, если существует
item = {
"id": "item-002",
"category": "electronics",
"name": "Tablet",
"price": 499.99
}
result = container.upsert_item(body=item)
Удаление элемента
container.delete_item(
item="item-001",
partition_key="electronics"
)
Запросы
Базовый запрос
# Запрос внутри раздела (эффективный)
query = "SELECT * FROM c WHERE c.price < @max_price"
items = container.query_items(
query=query,
parameters=[{"name": "@max_price", "value": 500}],
partition_key="electronics"
)
for item in items:
print(f"{item['name']}: ${item['price']}")
</code></pre>
<h3>Межпартиционный запрос</h3>
<pre><code class="language-python"># Межпартиционный (более ресурсоемкий, использовать с осторожностью)
query = "SELECT * FROM c WHERE c.price < @max_price"
items = container.query_items(
query=query,
parameters=[{"name": "@max_price", "value": 500}],
enable_cross_partition_query=True
)
for item in items:
print(item)
</code></pre>
<h3>Запрос с проекцией</h3>
<pre><code class="language-python">query = "SELECT c.id, c.name, c.price FROM c WHERE c.category = @category"
items = container.query_items(
query=query,
parameters=[{"name": "@category", "value": "electronics"}],
partition_key="electronics"
)
</code></pre>
<h3>Чтение всех элементов</h3>
<pre><code class="language-python"># Чтение всех элементов в одном разделе
items = container.read_all_items() # Чтение по всем разделам
# Или с использованием ключа раздела
items = container.query_items(
query="SELECT * FROM c",
partition_key="electronics"
)
</code></pre>
<h2>Ключи раздела</h2>
<p><strong>Важно</strong>: всегда указывайте ключ раздела для обеспечения эффективности операций.</p>
<pre><code class="language-python">from azure.cosmos import PartitionKey
# Один ключ раздела
container = database.create_container_if_not_exists(
id="orders",
partition_key=PartitionKey(path="/customer_id")
)
# Иерархический ключ раздела (предварительная версия)
container = database.create_container_if_not_exists(
id="events",
partition_key=PartitionKey(path=["/tenant_id", "/user_id"])
)
</code></pre>
<h2>Пропускная способность</h2>
<pre><code class="language-python"># Создание контейнера с заданной пропускной способностью
container = database.create_container_if_not_exists(
id="mycontainer",
partition_key=PartitionKey(path="/pk"),
offer_throughput=400 # RU/s
)
# Чтение текущей пропускной способности
offer = container.read_offer()
print(f"Пропускная способность: {offer.offer_throughput} RU/s")
# Обновление пропускной способности
container.replace_throughput(throughput=1000)
</code></pre>
<h2>Асинхронный клиент</h2>
<pre><code class="language-python">from azure.cosmos.aio import CosmosClient
from azure.identity.aio import DefaultAzureCredential
async def cosmos_operations():
async with DefaultAzureCredential() as credential:
async with CosmosClient(endpoint, credential=credential) as client:
database = client.get_database_client("mydb")
container = database.get_container_client("mycontainer")
# Создание
await container.create_item(body={"id": "1", "pk": "test"})
# Чтение
item = await container.read_item(item="1", partition_key="test")
# Запрос
async for item in container.query_items(
query="SELECT * FROM c",
partition_key="test"
):
print(item)
import asyncio
asyncio.run(cosmos_operations())
</code></pre>
<h2>Обработка ошибок</h2>
<pre><code class="language-python">from azure.cosmos.exceptions import CosmosHttpResponseError
try:
item = container.read_item(item="nonexistent", partition_key="pk")
except CosmosHttpResponseError as e:
if e.status_code == 404:
print("Элемент не найден")
elif e.status_code == 429:
print(f"Ограничение частоты запросов. Повторите попытку через: {e.headers.get('x-ms-retry-after-ms')} мс")
else:
raise
</code></pre>
<h2>Рекомендации</h2>
<ol>
<li><strong>Выбирайте синхронный ИЛИ асинхронный режим и придерживайтесь его.</strong> Не смешивайте <code>azure.cosmos</code> синхронных клиентов с <code>azure.cosmos.aio</code> асинхронными клиентами в одном пути вызова. Выбирайте один режим для каждого модуля.</li>
<li><strong>Всегда используйте контекстные менеджеры для клиентов и асинхронных учетных данных.</strong> Оборачивайте каждого клиента в <code>with CosmosClient(...) as client:</code> (синхронный режим) или <code>async with CosmosClient(...) as client:</code> (асинхронный режим). Для асинхронного режима <code>DefaultAzureCredential</code> из <code>azure.identity.aio</code> также используйте <code>async with credential:</code>, чтобы обеспечить очистку токенов и транспортных данных.</li>
<li><strong>Используйте <code>DefaultAzureCredential</code></strong> для переносимой аутентификации между локальной средой разработки и Azure (по возможности избегайте строк подключения / ключей API).</li>
<li><strong>Всегда указывайте ключ раздела</strong> для точечных чтений и запросов</li>
<li><strong>Используйте параметризованные запросы</strong> для предотвращения инъекций и улучшения кэширования</li>
<li><strong>По возможности избегайте межпартиционных запросов</strong></li>
<li><strong>Используйте <code>upsert_item</code></strong> для идемпотентной записи</li>
<li><strong>Используйте асинхронный клиент</strong> для сценариев с высокой пропускной способностью</li>
<li><strong>Проектируйте ключ раздела</strong> для равномерного распределения данных</li>
<li><strong>Используйте <code>read_item</code></strong> вместо запроса для извлечения отдельного документа</li>
</ol>
<h2>Справочные файлы</h2>
<table>
<thead>
<tr>
<th>Файл</th>
<th>Содержание</th>
</tr>
</thead>
<tbody><tr>
<td>references/partitioning.md</td>
<td>Стратегии ключей разбиения, иерархические ключи, обнаружение «горячих» разбиений и меры по их устранению</td>
</tr>
<tr>
<td>references/query-patterns.md</td>
<td>Оптимизация запросов, агрегации, пагинация, транзакции, канал изменений</td>
</tr>
<tr>
<td>scripts/setup_cosmos_container.py</td>
<td>Инструмент командной строки для создания контейнеров с разбиением на партиции, пропускной способностью и индексированием</td>
</tr>
</tbody></table> ---
name: azure-cosmos-py
description: Perform CRUD operations, run queries, and manage containers on Azure Cosmos DB NoSQL API using the Python SDK.
license: MIT
---
# Azure Cosmos DB SDK for Python
Client library for Azure Cosmos DB NoSQL API — globally distributed, multi-model database.
## 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=mydb # Required for all auth methods
COSMOS_CONTAINER=mycontainer # Required for all auth methods
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.cosmos import CosmosClient
# 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>.documents.azure.com:443/"
with CosmosClient(url=endpoint, credential=credential) as client:
# Use client here (see following sections for operations)
...
```
## Client Hierarchy
| Client | Purpose | Get From |
|--------|---------|----------|
| `CosmosClient` | Account-level operations | Direct instantiation |
| `DatabaseProxy` | Database operations | `client.get_database_client()` |
| `ContainerProxy` | Container/item operations | `database.get_container_client()` |
## Core Workflow
### Setup Database and Container
```python
# Get or create database
database = client.create_database_if_not_exists(id="mydb")
# Get or create container with partition key
container = database.create_container_if_not_exists(
id="mycontainer",
partition_key=PartitionKey(path="/category")
)
# Get existing
database = client.get_database_client("mydb")
container = database.get_container_client("mycontainer")
```
### Create Item
```python
item = {
"id": "item-001", # Required: unique within partition
"category": "electronics", # Partition key value
"name": "Laptop",
"price": 999.99,
"tags": ["computer", "portable"]
}
created = container.create_item(body=item)
print(f"Created: {created['id']}")
```
### Read Item
```python
# Read requires id AND partition key
item = container.read_item(
item="item-001",
partition_key="electronics"
)
print(f"Name: {item['name']}")
```
### Update Item (Replace)
```python
item = container.read_item(item="item-001", partition_key="electronics")
item["price"] = 899.99
item["on_sale"] = True
updated = container.replace_item(item=item["id"], body=item)
```
### Upsert Item
```python
# Create if not exists, replace if exists
item = {
"id": "item-002",
"category": "electronics",
"name": "Tablet",
"price": 499.99
}
result = container.upsert_item(body=item)
```
### Delete Item
```python
container.delete_item(
item="item-001",
partition_key="electronics"
)
```
## Queries
### Basic Query
```python
# Query within a partition (efficient)
query = "SELECT * FROM c WHERE c.price < @max_price"
items = container.query_items(
query=query,
parameters=[{"name": "@max_price", "value": 500}],
partition_key="electronics"
)
for item in items:
print(f"{item['name']}: ${item['price']}")
```
### Cross-Partition Query
```python
# Cross-partition (more expensive, use sparingly)
query = "SELECT * FROM c WHERE c.price < @max_price"
items = container.query_items(
query=query,
parameters=[{"name": "@max_price", "value": 500}],
enable_cross_partition_query=True
)
for item in items:
print(item)
```
### Query with Projection
```python
query = "SELECT c.id, c.name, c.price FROM c WHERE c.category = @category"
items = container.query_items(
query=query,
parameters=[{"name": "@category", "value": "electronics"}],
partition_key="electronics"
)
```
### Read All Items
```python
# Read all in a partition
items = container.read_all_items() # Cross-partition
# Or with partition key
items = container.query_items(
query="SELECT * FROM c",
partition_key="electronics"
)
```
## Partition Keys
**Critical**: Always include partition key for efficient operations.
```python
from azure.cosmos import PartitionKey
# Single partition key
container = database.create_container_if_not_exists(
id="orders",
partition_key=PartitionKey(path="/customer_id")
)
# Hierarchical partition key (preview)
container = database.create_container_if_not_exists(
id="events",
partition_key=PartitionKey(path=["/tenant_id", "/user_id"])
)
```
## Throughput
```python
# Create container with provisioned throughput
container = database.create_container_if_not_exists(
id="mycontainer",
partition_key=PartitionKey(path="/pk"),
offer_throughput=400 # RU/s
)
# Read current throughput
offer = container.read_offer()
print(f"Throughput: {offer.offer_throughput} RU/s")
# Update throughput
container.replace_throughput(throughput=1000)
```
## Async Client
```python
from azure.cosmos.aio import CosmosClient
from azure.identity.aio import DefaultAzureCredential
async def cosmos_operations():
async with DefaultAzureCredential() as credential:
async with CosmosClient(endpoint, credential=credential) as client:
database = client.get_database_client("mydb")
container = database.get_container_client("mycontainer")
# Create
await container.create_item(body={"id": "1", "pk": "test"})
# Read
item = await container.read_item(item="1", partition_key="test")
# Query
async for item in container.query_items(
query="SELECT * FROM c",
partition_key="test"
):
print(item)
import asyncio
asyncio.run(cosmos_operations())
```
## Error Handling
```python
from azure.cosmos.exceptions import CosmosHttpResponseError
try:
item = container.read_item(item="nonexistent", partition_key="pk")
except CosmosHttpResponseError as e:
if e.status_code == 404:
print("Item not found")
elif e.status_code == 429:
print(f"Rate limited. Retry after: {e.headers.get('x-ms-retry-after-ms')}ms")
else:
raise
```
## Best Practices
1. **Pick sync OR async and stay consistent.** Do not mix `azure.cosmos` sync clients with `azure.cosmos.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 CosmosClient(...) as client:` (sync) or `async with CosmosClient(...) 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. **Always specify partition key** for point reads and queries
5. **Use parameterized queries** to prevent injection and improve caching
6. **Avoid cross-partition queries** when possible
7. **Use `upsert_item`** for idempotent writes
8. **Use async client** for high-throughput scenarios
9. **Design partition key** for even data distribution
10. **Use `read_item`** instead of query for single document retrieval
## Reference Files
| File | Contents |
|------|----------|
| [references/partitioning.md](references/partitioning.md) | Partition key strategies, hierarchical keys, hot partition detection and mitigation |
| [references/query-patterns.md](references/query-patterns.md) | Query optimization, aggregations, pagination, transactions, change feed |
| [scripts/setup_cosmos_container.py](scripts/setup_cosmos_container.py) | CLI tool for creating containers with partitioning, throughput, and indexing |
Все файлы
0 файловУстановить azure-cosmos-py
Скачайте файлы навыков и распакуйте их в каталог .claude/skills/.
Скачать ZIPКлонируйте репозиторий и скопируйте файлы навыка в свой проект.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-cosmos-py # Copy SKILL.md to your .claude/skills/ directory
Копировать





Дом
