Chuyển đến nội dung
Skillpedia
Cơ sở dữ liệu48k · #3916

azure-cosmos-db-py

Skill này làm gì

Đoạn mã này giúp xây dựng và quản lý dữ liệu trong cơ sở dữ liệu có tên Azure Cosmos DB. Nó đảm bảo dữ liệu được lưu trữ có tổ chức và an toàn, theo các thực hành lập trình tốt.

Khi nào nên dùng

  • ✓Khi bạn tạo một dịch vụ dữ liệu mới cho ứng dụng.
  • ✓Khi bạn cần đảm bảo dữ liệu được lưu trữ an toàn.
  • ✓Khi bạn phát triển ứng dụng dùng Azure Cosmos DB.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/azure-cosmos-db-py/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/azure-cosmos-db-py/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Thiết lập cơ sở dữ liệu Azure Cosmos DB cho ứng dụng của tôi.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Đoạn mã kết nối với Azure Cosmos DB bằng thông tin xác thực an toàn. Nó tổ chức dữ liệu thành các mô hình và đảm bảo các thao tác được thực hiện hiệu quả và an toàn.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Bundled upstream support

Supporting files are included at skill-relative paths. See UPSTREAM-NOTICE.md for their pinned sources, licenses, hashes, and import changes.

Restored helper safety

The integration fixture in assets/conftest_template.py connects to the configured Cosmos endpoint; cleanup_test_docs deletes records explicitly added to its tracking list. Use only an isolated disposable test container with test-only records, never production data. Copying the template does not connect to Cosmos.

Cosmos DB Service Implementation

Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.

Installation

pip install azure-cosmos azure-identity

Environment Variables

COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/
COSMOS_DATABASE_NAME=<database-name>
COSMOS_CONTAINER_ID=<container-id>
# For emulator only (not production)
COSMOS_KEY=<emulator-key>

Authentication

DefaultAzureCredential (preferred):

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

client = CosmosClient(
    url=os.environ["COSMOS_ENDPOINT"],
    credential=DefaultAzureCredential()
)

Emulator (local development):

from azure.cosmos import CosmosClient

client = CosmosClient(
    url="https://localhost:8081",
    credential=os.environ["COSMOS_KEY"],
    connection_verify=False
)

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:

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

2. Pydantic Model Hierarchy

Use five-tier model pattern for clean separation:

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")


…
Câu hỏi thường gặp

Azure Cosmos DB là gì?

Đó là dịch vụ cơ sở dữ liệu NoSQL của Microsoft, cho phép bạn lưu và truy vấn dữ liệu nhanh chóng ở quy mô lớn.

“Clean code best practices” là gì?

Đó là các phương pháp và quy ước giúp mã dễ hiểu, dễ bảo trì và an toàn hơn, như sắp xếp mã có tổ chức và tránh các lỗi phổ biến.

TDD là gì?

TDD là viết tắt của Test-Driven Development (phát triển hướng kiểm thử). Đây là cách viết kiểm thử trước khi viết mã chính, để đảm bảo mọi thứ hoạt động như mong đợi.

Chi tiết

Mô tả gốc của tác giả

Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#3916
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự