본문으로 건너뛰기
Skillpedia
데이터베이스48k · #3916

azure-cosmos-db-py

하는 일

Azure Cosmos DB라는 데이터베이스에서 데이터를 만들고 관리하도록 돕는 코드입니다. 좋은 프로그래밍 관행을 따라 데이터를 체계적이고 안전한 방식으로 저장하도록 합니다.

사용하는 경우

  • ✓애플리케이션을 위한 새 데이터 서비스를 만들 때.
  • ✓데이터가 안전하게 저장되어야 할 때.
  • ✓Azure Cosmos DB를 사용하는 애플리케이션을 개발할 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/azure-cosmos-db-py/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“제 애플리케이션을 위한 Azure Cosmos DB 데이터베이스를 설정해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 코드는 안전한 자격 증명으로 Azure Cosmos DB에 연결합니다. 데이터를 모델로 정리하고, 작업이 효율적이고 안전하게 수행되도록 합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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


…
자주 묻는 질문

Azure Cosmos DB는 무엇인가요?

Microsoft의 NoSQL 데이터베이스 서비스로, 데이터를 빠르고 대규모로 저장하고 조회할 수 있게 해 줍니다.

‘클린 코드 모범 사례’는 무엇인가요?

코드를 이해하기 쉽고, 유지보수하기 쉽고, 안전하게 만드는 방법과 관례입니다. 예를 들어 코드를 체계적으로 정리하고 흔한 오류를 피하는 것입니다.

TDD는 무엇인가요?

Test-Driven Development(테스트 주도 개발)의 약자로, 본 코드를 쓰기 전에 테스트를 먼저 작성해 모든 것이 기대대로 작동하도록 하는 방식입니다.

상세 정보

작성자의 원본 설명

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

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#3916
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬