Python配置

Mattakushi4322026-10-26查看 1853复制 141

何时激活:配置管理、pydantic-settings、env 文件、功能标志、特定于环境的设置

Download (.md)

📘如何使用这个技能

  1. 1
    复制技能内容·点击上方「Copy SKILL.md」复制全部内容,或 Download 下载到本地
  2. 2
    打开你的 AI 客户端·支持 Claude Code、Trae、Cursor、ChatGPT、DeepSeek、Kimi 等任意 AI 助手
  3. 3
    粘贴为系统提示/知识文件·Claude Code:放入 .claude/skills/ 目录;普通对话:作为首条消息发送并说「请严格按这份技能文档执行」
  4. 4
    直接提出你的需求·AI 会按技能定义的工作流、格式和约束来处理,无需再解释背景

💡 提示:技能生效后,每次对话只需一句需求,AI 会按 SKILL.md 的流程执行。

SKILL.md3103 chars
---
name: python-config
description: "When to activate: configuration management, pydantic-settings, env files, feature flags, environment-specific settings"
origin: zakr
metadata:
  namespace: zakr/devtools-pack
  version: 1.0.0
  category: engineering
  language: python
  platforms: [claude-code, codex, gemini-cli, cursor, aider, windsurf]
---

# Python Configuration Patterns

## Pydantic Settings (12-Factor App)
```python
from pydantic import PostgresDsn, RedisDsn, SecretStr, AnyHttpUrl, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from functools import lru_cache

class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
    )
    
    # Application
    app_name: str = "MyApp"
    environment: str = "development"  # development | staging | production
    debug: bool = False
    
    # Database
    database_url: PostgresDsn
    database_pool_size: int = 10
    database_max_overflow: int = 20
    
    # Cache
    redis_url: RedisDsn = "redis://localhost:6379/0"
    
    # Auth
    secret_key: SecretStr
    access_token_expire_minutes: int = 30
    
    # External services
    sendgrid_api_key: SecretStr | None = None
    stripe_secret_key: SecretStr | None = None
    
    @field_validator("environment")
    @classmethod
    def validate_env(cls, v: str) -> str:
        allowed = {"development", "staging", "production"}
        if v not in allowed:
            raise ValueError(f"environment must be one of {allowed}")
        return v
    
    @property
    def is_production(self) -> bool:
        return self.environment == "production"

@lru_cache
def get_settings() -> Settings:
    return Settings()

# Usage in FastAPI
settings = Annotated[Settings, Depends(get_settings)]
```

## Environment-Specific Settings
```python
# config/base.py
class BaseConfig(BaseSettings):
    debug: bool = False
    log_level: str = "INFO"
    database_url: PostgresDsn
    
# config/development.py
class DevelopmentConfig(BaseConfig):
    debug: bool = True
    log_level: str = "DEBUG"

# config/production.py
class ProductionConfig(BaseConfig):
    debug: bool = False
    # Production enforces certain required fields
    sentry_dsn: AnyHttpUrl

def get_config() -> BaseConfig:
    env = os.getenv("ENVIRONMENT", "development")
    configs = {
        "development": DevelopmentConfig,
        "production": ProductionConfig,
    }
    return configs.get(env, DevelopmentConfig)()
```

## Feature Flags
```python
from pydantic import BaseModel

class FeatureFlags(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="FEATURE_")
    
    new_dashboard: bool = False
    ai_recommendations: bool = False
    beta_api: bool = False

flags = FeatureFlags()

# Usage
if flags.new_dashboard:
    return new_dashboard_response()

# Runtime flags from Redis (for fast toggling without redeploy)
async def is_enabled(feature: str, redis: Redis) -> bool:
    raw = await redis.get(f"feature:{feature}")
    return raw == b"true" if raw else False
```
来源:skillsdirectory

评论0

登录后参与评论

还没有评论,来抢沙发吧