Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)41k · #6759

python-configuration

Skill này làm gì

Công cụ này giúp tổ chức thiết lập của chương trình. Thay vì viết các giá trị quan trọng (như mật khẩu hoặc địa chỉ website) trực tiếp trong code, nó đọc chúng từ biến môi trường, giúp chương trình linh hoạt và an toàn hơn.

Khi nào nên dùng

  • ✓Khi bạn bắt đầu một dự án mới và muốn tổ chức cấu hình của nó.
  • ✓Khi bạn cần cùng một code chạy được ở các môi trường khác nhau (như phát triển và thực tế).
  • ✓Khi bạn cần quản lý an toàn thông tin nhạy cảm, như mật khẩu và API key.

Liên kết skill

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-configuration/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/wshobson/agents/blob/main/plugins/python-development/skills/python-configuration/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

“Làm sao để ứng dụng của tôi dùng biến môi trường cho cơ sở dữ liệu và API key?”

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

Cách hoạt động

Công cụ dùng thư viện Pydantic để định nghĩa các thiết lập cần có và kiểu của chúng (văn bản, số, v.v.). Khi chương trình khởi động, nó kiểm tra xem tất cả các thiết lập cần thiết đã được cung cấp qua biến môi trường chưa và tải chúng.

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.

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)

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

Tại sao không ghi mật khẩu trực tiếp trong code?

Ghi mật khẩu và thông tin nhạy cảm khác trực tiếp trong code là không an toàn. Nếu code bị chia sẻ hoặc vô tình lộ ra, thông tin này có thể bị đánh cắp. Dùng biến môi trường giúp giữ thông tin này ngoài code chính.

“Biến môi trường” là gì?

Đây là các giá trị bạn thiết lập trong hệ điều hành nơi chương trình chạy. Chương trình có thể đọc các giá trị này mà không cần ghi trực tiếp trong code. Ví dụ, bạn có thể đặt một biến tên `DATABASE_URL` chứa địa chỉ cơ sở dữ liệu.

Điều gì xảy ra nếu thiếu một cấu hình quan trọng?

Chương trình sẽ dừng ngay từ đầu và hiển thị thông báo rõ ràng về cấu hình nào bị thiếu. Điều này tốt hơn là chương trình lỗi về sau theo cách khó hiểu.

Chi tiết

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

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

Độ phổ biến

Sao GitHub
41k
Vị trí xếp hạng
#6759
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ự