Configuration Management¶
Pydantic Settings¶
Use pydantic-settings for validated, typed configuration:
from pydantic import SecretStr, computed_field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
)
# Database
database_url: str
# Auth
secret_key: SecretStr
access_token_expire_minutes: int = 30
# External services
redis_url: str = "redis://localhost:6379/0"
smtp_host: str = "localhost"
smtp_port: int = 587
@computed_field
@property
def async_database_url(self) -> str:
return self.database_url.replace(
"postgresql://", "postgresql+asyncpg://"
)
settings = Settings()
Rules:
- Secrets use
SecretStr— they won't appear in logs or repr - All settings have types and defaults where sensible
- Validation happens at startup — fail fast on misconfiguration
- Use
@computed_fieldfor derived values
See Also¶
- Secrets Management -- Secure handling of API keys, tokens, and credentials
- Dependency Injection -- Injecting Settings and configuration via FastAPI Depends