Zum Inhalt springen
Skillpedia
APIs & Server (Backend)41k · #6759

python-configuration

Was er macht

Dieses Tool hilft dir, die Einstellungen eines Programms zu organisieren. Statt wichtige Werte (etwa Passwörter oder Webadressen) direkt im Code zu schreiben, liest es sie aus Umgebungsvariablen. Das macht das Programm flexibler und sicherer.

Wann du ihn nutzt

  • ✓Beim Start eines neuen Projekts, wenn du seine Konfiguration ordnen willst.
  • ✓Wenn derselbe Code in verschiedenen Umgebungen laufen soll, etwa in Entwicklung und Produktion.
  • ✓Um sensible Daten wie Passwörter und API-Keys sicher zu verwalten.

Link zum Skill

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

Kopiere ihn und füge ihn in deine KI ein (Claude, ChatGPT oder Cursor) mit der Bitte, den Anweisungen zu folgen.

So nutzt du ihn

Am einfachsten: Kopiere die Nachricht und füge sie in deine KI ein. Sie liest den Skill und folgt den Anweisungen.

Fertige Nachricht zum Einfügen

Nutze diesen Skill, um mir zu helfen: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-configuration/SKILL.md Lies die SKILL.md unter diesem Link und folge ihren Anweisungen für meine Aufgabe.
Soll deine KI Skills wie diesen selbst finden?Installiere den kostenlosen Skillpedia-MCP: eine Zeile, und sie durchsucht vor jeder Aufgabe 15.000+ Skills.In 1 Minute installieren →

Beispielanfrage an deine KI

“Wie richte ich meine Anwendung so ein, dass sie Umgebungsvariablen für die Datenbank und die API-Keys nutzt?”

5 neue Skills pro Woche. 1 Minute Lesezeit.

So funktioniert es

Es nutzt die Bibliothek Pydantic, um festzulegen, welche Einstellungen erwartet werden und welchen Typ sie haben (Text, Zahl usw.). Beim Start prüft das Programm, ob alle nötigen Einstellungen über Umgebungsvariablen vorhanden sind, und lädt sie.

Technischer Inhalt (originale SKILL.md)

Originaltext des Autors, auf Englisch, direkt von 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)

…
Häufige Fragen

Warum nicht Passwörter direkt in den Code schreiben?

Passwörter und andere sensible Daten direkt im Code zu speichern ist unsicher. Wird der Code geteilt oder versehentlich veröffentlicht, lassen sich diese Daten stehlen. Mit Umgebungsvariablen bleiben sie aus dem Hauptcode heraus.

Was sind 'Umgebungsvariablen'?

Das sind Werte, die du im Betriebssystem setzt, auf dem das Programm läuft. Das Programm kann sie lesen, ohne dass sie im Code stehen. Du kannst zum Beispiel eine Variable namens `DATABASE_URL` mit deiner Datenbankadresse setzen.

Was passiert, wenn eine wichtige Konfiguration fehlt?

Das Programm stoppt direkt am Anfang und zeigt eine klare Meldung, welche Konfiguration fehlt. Das ist besser, als wenn es später auf verwirrende Weise abbricht.

Details

Originalbeschreibung des Autors

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

Beliebtheit

GitHub-Sterne
41k
Platz im Ranking
#6759
Lizenz
MIT
Aktualisiert
15.10.2026

Ist dieser Skill nützlich?

0

Anmelden um abzustimmen.

Kommentare

  • …

Weitere Skills aus diesem Repository

Ähnliche Skills