본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)41k · #6759

python-configuration

하는 일

이 도구는 컴퓨터 프로그램의 설정을 정리하도록 돕습니다. 비밀번호나 웹 주소처럼 중요한 값을 코드에 직접 쓰지 않고 환경 변수에서 읽어 와서, 프로그램을 더 유연하고 안전하게 만듭니다.

사용하는 경우

  • ✓새 프로젝트를 시작하고 설정을 정리하고 싶을 때.
  • ✓같은 코드를 개발 환경과 실제 운영 환경 등 여러 환경에서 작동시켜야 할 때.
  • ✓비밀번호나 API 키 같은 민감한 정보를 안전하게 관리할 때.

스킬 링크

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-configuration/SKILL.md

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

사용 방법

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

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

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

AI에게 요청하는 예시

“데이터베이스와 API 키에 환경 변수를 사용하도록 애플리케이션을 어떻게 설정할 수 있나요?”

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

작동 방식

Pydantic이라는 라이브러리를 사용해 필요한 설정과 그 타입(문자, 숫자 등)을 정의합니다. 프로그램이 시작될 때 필요한 모든 설정이 환경 변수로 제공되었는지 확인하고 그 값을 불러옵니다.

기술 내용 (원본 SKILL.md)

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

Python Configuration Management

Externalize configuration from code using environment variables and typed settings. Well-managed configuration enables the same code to run in any environment without modification.

When to Use This Skill

  • Setting up a new project's configuration system
  • Migrating from hardcoded values to environment variables
  • Implementing pydantic-settings for typed configuration
  • Managing secrets and sensitive values
  • Creating environment-specific settings (dev/staging/prod)
  • Validating configuration at application startup

Core Concepts

1. Externalized Configuration

All environment-specific values (URLs, secrets, feature flags) come from environment variables, not code.

2. Typed Settings

Parse and validate configuration into typed objects at startup, not scattered throughout code.

3. Fail Fast

Validate all required configuration at application boot. Missing config should crash immediately with a clear message.

4. Sensible Defaults

Provide reasonable defaults for local development while requiring explicit values for sensitive settings.

Quick Start

from pydantic_settings import BaseSettings
from pydantic import Field

class Settings(BaseSettings):
    database_url: str = Field(alias="DATABASE_URL")
    api_key: str = Field(alias="API_KEY")
    debug: bool = Field(default=False, alias="DEBUG")

settings = Settings()  # Loads from environment

Fundamental Patterns

Pattern 1: Typed Settings with Pydantic

Create a central settings class that loads and validates all configuration.

from pydantic_settings import BaseSettings
from pydantic import Field, PostgresDsn, ValidationError
import sys

class Settings(BaseSettings):
    """Application configuration loaded from environment variables."""

    # Database
    db_host: str = Field(alias="DB_HOST")
    db_port: int = Field(default=5432, alias="DB_PORT")
    db_name: str = Field(alias="DB_NAME")
    db_user: str = Field(alias="DB_USER")
    db_password: str = Field(alias="DB_PASSWORD")

    # Redis
    redis_url: str = Field(default="redis://localhost:6379", alias="REDIS_URL")

    # API Keys
    api_secret_key: str = Field(alias="API_SECRET_KEY")

    # Feature flags
    enable_new_feature: bool = Field(default=False, alias="ENABLE_NEW_FEATURE")

    model_config = {
        "env_file": ".env",
        "env_file_encoding": "utf-8",
    }

# Create singleton instance at module load
try:
    settings = Settings()
except ValidationError as e:
    print(f"Configuration error:\n{e}")
    sys.exit(1)

Import settings throughout your application:

from myapp.config import settings

def get_database_connection():
    return connect(
        host=settings.db_host,
        port=settings.db_port,
        database=settings.db_name,
    )

Pattern 2: Fail Fast on Missing Configuration

Required settings should crash the application immediately with a clear error.

from pydantic_settings import BaseSettings
from pydantic import Field, ValidationError
import sys

class Settings(BaseSettings):
    # Required - no default means it must be set
    api_key: str = Field(alias="API_KEY")
    database_url: str = Field(alias="DATABASE_URL")

    # Optional with defaults
    log_level: str = Field(default="INFO", alias="LOG_LEVEL")

try:
    settings = Settings()
except ValidationError as e:
    print("=" * 60)
    print("CONFIGURATION ERROR")
    print("=" * 60)
    for error in e.errors():
        field = error["loc"][0]
        print(f"  - {field}: {error['msg']}")
    print("\nPlease set the required environment variables.")
    sys.exit(1)

A clear error at startup is better than a cryptic None failure mid-request.

Pattern 3: Local Development Defaults

Provide sensible defaults for local development while requiring explicit values for secrets.

class Settings(BaseSettings):
    # Has local default, but prod will override
    db_host: str = Field(default="localhost", alias="DB_HOST")
    db_port: int = Field(default=5432, alias="DB_PORT")

    # Always required - no default for secrets
    db_password: str = Field(alias="DB_PASSWORD")
    api_secret_key: str = Field(alias="API_SECRET_KEY")

    # Development convenience
    debug: bool = Field(default=False, alias="DEBUG")

    model_config = {"env_file": ".env"}

Create a .env file for local development (never commit this):

# .env (add to .gitignore)

…
자주 묻는 질문

왜 비밀번호를 코드에 직접 넣으면 안 되나요?

비밀번호와 기타 민감한 정보를 코드에 직접 넣는 것은 안전하지 않습니다. 코드가 공유되거나 실수로 노출되면 이 정보가 도난당할 수 있습니다. 환경 변수를 사용하면 이 정보가 주요 코드 밖에 머뭅니다.

'환경 변수'란 무엇인가요?

프로그램이 실행되는 운영체제에 설정하는 값입니다. 프로그램은 코드에 직접 적히지 않아도 이 값을 읽을 수 있습니다. 예를 들어 `DATABASE_URL`이라는 이름으로 데이터베이스 주소를 설정할 수 있습니다.

중요한 설정이 빠져 있으면 어떻게 되나요?

프로그램이 시작하자마자 멈추고, 어떤 설정이 빠졌는지 명확하게 알려 줍니다. 이는 나중에 프로그램이 혼란스럽게 실패하는 것보다 낫습니다.

상세 정보

작성자의 원본 설명

Python configuration management via environment variables and typed settings. Use when externalizing config, setting up pydantic-settings, managing secrets, or implementing environment-specific behavior.

repo: wshobson/agents

인기도

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

이 스킬이 유용한가요?

0

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

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬