← 返回 Skills 市场
thegovind

Azure Cosmos DB Python

作者 thegovind · GitHub ↗ · v0.1.0
cross-platform ⚠ suspicious
1451
总下载
1
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install azure-cosmos-py
功能描述
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".
使用说明 (SKILL.md)

Azure Cosmos DB SDK for Python

Client library for Azure Cosmos DB NoSQL API — globally distributed, multi-model database.

Installation

pip install azure-cosmos azure-identity

Environment Variables

COSMOS_ENDPOINT=https://\x3Caccount>.documents.azure.com:443/
COSMOS_DATABASE=mydb
COSMOS_CONTAINER=mycontainer

Authentication

from azure.identity import DefaultAzureCredential
from azure.cosmos import CosmosClient

credential = DefaultAzureCredential()
endpoint = "https://\x3Caccount>.documents.azure.com:443/"

client = CosmosClient(url=endpoint, credential=credential)

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

# 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

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

# Read requires id AND partition key
item = container.read_item(
    item="item-001",
    partition_key="electronics"
)
print(f"Name: {item['name']}")

Update Item (Replace)

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

# 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

container.delete_item(
    item="item-001",
    partition_key="electronics"
)

Queries

Basic Query

# Query within a partition (efficient)
query = "SELECT * FROM c WHERE c.price \x3C @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

# Cross-partition (more expensive, use sparingly)
query = "SELECT * FROM c WHERE c.price \x3C @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

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

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

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

# 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

from azure.cosmos.aio import CosmosClient
from azure.identity.aio import DefaultAzureCredential

async def cosmos_operations():
    credential = DefaultAzureCredential()
    
    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

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. Always specify partition key for point reads and queries
  2. Use parameterized queries to prevent injection and improve caching
  3. Avoid cross-partition queries when possible
  4. Use upsert_item for idempotent writes
  5. Use async client for high-throughput scenarios
  6. Design partition key for even data distribution
  7. Use read_item instead of query for single document retrieval

Reference Files

File Contents
references/partitioning.md Partition key strategies, hierarchical keys, hot partition detection and mitigation
references/query-patterns.md Query optimization, aggregations, pagination, transactions, change feed
scripts/setup_cosmos_container.py CLI tool for creating containers with partitioning, throughput, and indexing
安全使用建议
This skill appears to be a legitimate Cosmos DB helper, but exercise caution before installing or running its script. Key points: - Metadata omission: the skill metadata lists no required environment variables, yet SKILL.md and the included script require COSMOS_ENDPOINT and may use COSMOS_KEY or DefaultAzureCredential. Ask the publisher to declare required env vars explicitly. - High‑privilege credential: COSMOS_KEY is an account key that grants broad read/write/admin access. Do NOT provide a production account key to an untrusted skill. Prefer using a least‑privilege service principal or managed identity with only the needed permissions. - DefaultAzureCredential caveat: DefaultAzureCredential can pick up credentials from many sources (dev tooling, Azure CLI, managed identity). Be aware which identity will be used in your environment. - Code quality: the included setup_cosmos_container.py has a visible syntax/logic bug (malformed append of excluded path) which may cause runtime crashes — review/fix before running. The script will create containers, change throughput, and can run cross‑partition queries that enumerate counts of all items (possible data exposure), so test against a non‑production account first. Recommendations: ask the publisher for source/homepage, require them to update metadata to list required env vars, inspect and/or lint the script locally, and run only with a scoped test account or role with least privilege.
功能分析
Type: OpenClaw Skill Name: azure-cosmos-py Version: 0.1.0 The skill bundle is benign. It provides documentation and a Python CLI tool for managing Azure Cosmos DB containers. The `SKILL.md` file is purely instructional and contains no prompt injection attempts. The `scripts/setup_cosmos_container.py` script legitimately uses `COSMOS_ENDPOINT` and `COSMOS_KEY` environment variables for authentication to Azure Cosmos DB, which is necessary for its stated purpose of creating and configuring containers. There is no evidence of data exfiltration, malicious execution, persistence, or obfuscation.
能力评估
Purpose & Capability
Name/description, SKILL.md examples, and the setup script all target Azure Cosmos DB NoSQL operations (create containers, partitioning, CRUD, queries). The requested capabilities are consistent with the stated purpose.
Instruction Scope
The runtime instructions and included CLI script expect COSMOS_ENDPOINT and optionally COSMOS_KEY (or DefaultAzureCredential). However the skill metadata declared no required environment variables. The setup script will perform management actions (create databases/containers, change throughput, run cross‑partition queries and count items) that have broad read/write privileges on the account — appropriate for a DB tool but potentially dangerous if run with full account keys or against production data. The SKILL.md and script do not instruct reading unrelated files, but they do rely on DefaultAzureCredential which may surface system or user credentials transparently.
Install Mechanism
There is no install spec (instruction-only). SKILL.md recommends pip packages (azure-cosmos, azure-identity) which is expected and low-risk. No arbitrary downloads or archive extraction are present.
Credentials
The registry declares no required env vars, but SKILL.md and scripts require COSMOS_ENDPOINT and may require COSMOS_KEY (or DefaultAzureCredential). COSMOS_KEY is a full account key (high privilege). The omission of required env vars from metadata is an incoherence and increases risk because users may not realize they are asked for account credentials.
Persistence & Privilege
The skill is not always-on and does not request persistent platform privileges. It does not modify other skills or global agent settings. Autonomous invocation is allowed (platform default) but not uniquely concerning here.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install azure-cosmos-py
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /azure-cosmos-py 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v0.1.0
Initial release of azure-cosmos-py — Azure Cosmos DB SDK for Python (NoSQL API). - Provides client library usage for document CRUD, queries, and container management. - Supports authentication with Azure Identity and .env configuration. - Detailed example workflows for creating, reading, updating, upserting, deleting, and querying items. - Includes guidance for partition keys, throughput settings, and async client usage. - Covers error handling and best practices for efficient operations. - Reference files included for partitioning, query patterns, and container setup scripts.
元数据
Slug azure-cosmos-py
版本 0.1.0
许可证
累计安装 0
当前安装数 0
历史版本数 1
常见问题

Azure Cosmos DB Python 是什么?

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". 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 1451 次。

如何安装 Azure Cosmos DB Python?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install azure-cosmos-py」即可一键安装,无需额外配置。

Azure Cosmos DB Python 是免费的吗?

是的,Azure Cosmos DB Python 完全免费(开源免费),可自由下载、安装和使用。

Azure Cosmos DB Python 支持哪些平台?

Azure Cosmos DB Python 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Azure Cosmos DB Python?

由 thegovind(@thegovind)开发并维护,当前版本 v0.1.0。

💬 留言讨论