К основному содержанию
скилл

azure-cosmos-py — скилл для Claude Code: Cosmos DB на Python

Подсказывает агенту, как работать с Azure Cosmos DB через Python SDK: CRUD документов, запросы, контейнеры, ключи разделов.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add microsoft/skills --skill azure-cosmos-py -a claude-code
Открыть на GitHub

Что делает azure-cosmos-py

Скилл от Microsoft описывает клиентскую библиотеку azure-cosmos для NoSQL API. Агент получает готовые шаблоны: создание базы и контейнера, чтение и замена документа, upsert, удаление, запросы с параметрами и проекцией. Иерархия клиентов разложена по полочкам — CosmosClient, DatabaseProxy, ContainerProxy.

Отдельный блок про аутентификацию. Советует DefaultAzureCredential: он работает и локально через Azure CLI, и в Azure через управляемую идентичность, без правок кода. Строкам подключения и ключам аккаунта здесь места не нашлось — они обходят аудит Entra и ротацию. В продакшене нужно выставить AZURE_TOKEN_CREDENTIALS=prod, иначе цепочка учётных данных не ограничится.

Ещё одно правило: каждый клиент оборачивается в контекстный менеджер, синхронный или асинхронный, чтобы сокеты и кэш токенов закрывались предсказуемо. Есть раздел про пропускную способность в RU/s и про иерархический ключ раздела. Установка тянет две библиотеки: pip install azure-cosmos azure-identity. Запросы без ключа раздела дороже — в примерах это помечено прямо.

Какие задачи решает

  • создать контейнер с ключом раздела и провизионной пропускной способностью
  • прочитать документ по id и значению ключа раздела
  • заменить поля документа без пересоздания записи
  • написать параметризованный запрос с проекцией по категории
  • перевести синхронный код на асинхронный клиент

Примеры запросов агенту

  • Покажи, как через azure-cosmos создать контейнер orders с ключом раздела /customer_id
  • Напиши запрос к Cosmos DB: выбрать документы дешевле 500 в разделе electronics
  • Переделай этот код на асинхронный CosmosClient с DefaultAzureCredential

Как установить azure-cosmos-py

1Через Skills CLI (Vercel)

npx skills add microsoft/skills --skill azure-cosmos-py -a claude-code

2Вручную: положить файлы

~/.claude/skills/azure-cosmos-py/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/azure-cosmos-py/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о azure-cosmos-py

Как установить azure-cosmos-py в Claude?

Выполните npx skills add microsoft/skills --skill azure-cosmos-py -a claude-code. После этого файл скилла лежит в ~/.claude/skills/azure-cosmos-py/SKILL.md.

Что делает azure-cosmos-py?

Даёт агенту справочник по Python SDK для Azure Cosmos DB: операции с документами, запросы, контейнеры, ключи разделов и пропускная способность.

Что нужно, чтобы код из скилла заработал?

Библиотеки azure-cosmos и azure-identity, а также переменные COSMOS_ENDPOINT, COSMOS_DATABASE и COSMOS_CONTAINER. В продакшене добавьте AZURE_TOKEN_CREDENTIALS=prod.

Исходный текст

SKILL.md · MIT
---
name: azure-cosmos-py
description: |
  Azure Cosmos DB SDK for Python (NoSQL API). Use for document CRUD, queries, containers, and globally distributed data.
  Triggers: "cosmos db", "CosmosClient", "container", "document", "NoSQL", "partition key".
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
  package: azure-cosmos
---

# 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 |

© Microsoft · MIT · microsoft/skills

Похожие скиллы

Всё по теме «Облака: AWS, Azure, GCP» →
cosmosdb-datamodeling официальный github Собирает требования к NoSQL-приложению и помогает спроектировать модель данных для Azure Cosmos DB. Подойдёт для разбора паттернов доступа и нагрузки. 8 700установок cosmosdb-best-practices cosmosdb-agent-kit Скилл с набором правил по Azure Cosmos DB: моделирование данных, ключи разделов, запросы, SDK. Пригодится, когда агент пишет или правит код под Cosmos DB. CX Codex +1 1 100установок dataverse-python-best-practices официальный github Правило для GitHub Copilot с рабочими шаблонами работы с Dataverse SDK для Python: авторизация, клиент, CRUD-операции. ★ 40 418звёзд репо azure-sql-database MicrosoftDocs Помогает проектировать, настраивать и чинить базы Azure SQL Database. Подсказывает лимиты, выбор тарифов vCore или DTU и выгружает свежую документацию Microsoft Learn. CX Codex +1 1 300установок azure-blob-storage MicrosoftDocs Скилл передаёт агенту базу знаний по Azure Blob Storage: настройку уровней доступа, SFTP, BlobFuse2 и безопасность. Пригодится при отладке хранилища и миграции данных. CX Codex +1 322установок azure-verified-modules hashicorp Скилл с обязательными требованиями Azure Verified Modules: проверяет и помогает писать Terraform-модули, которые проходят сертификацию AVM. CX Codex +1 3 300установок

Из того же набора64

Весь набор →
azure-resource-lookup Перечисляет и находит ресурсы Azure по подпискам и группам через Azure Resource Graph. Нужен, когда надо увидеть, что вообще развёрнуто. 2установок azure-prepare Готовит проект к деплою через Azure Developer CLI: пишет azure.yaml, инфраструктуру на Bicep или Terraform и Dockerfile. Нужен, когда вы уже выбрали azd. 2установок azure-search-documents-py Подсказывает агенту, как писать код для Azure AI Search на Python: векторный и гибридный поиск, семантический ранжинг, индексы. 2установок azure-eventhub-py Скилл для работы с Azure Event Hubs из Python: отправка событий, чтение партиций, чекпоинты в blob-хранилище. Пригодится, когда агент пишет продюсеров и консьюмеров. 2установок azure-appconfiguration-py Скилл учит агента работать с Azure App Configuration из Python: читать и записывать настройки, включать фича-флаги, снимать снапшоты. 2установок azure-ai-textanalytics-py Скилл для работы с Azure AI Language из Python: тональность, сущности, ключевые фразы, определение языка, поиск персональных данных и медицинский NLP. 2установок azure-upgrade Проводит оценку и автоматизирует переход Azure-нагрузок между планами, тарифами и SKU, а также обновляет устаревшие Azure SDK в коде. 1установок azure-compute Разбирает запросы про виртуальные машины Azure и VMSS: подбор размера, цены, создание, резервирование ёмкости. Пригодится, когда агент должен не гадать, а идти по нужному сценарию. 1установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой