Use pydantic-settings: a BaseSettings class reads typed values from environment variables and an optional .env file, fails fast when something required is missing, and can be cached and injected as a dependency (and overridden in tests).
Never commit secrets; load them from the environment or a secrets manager, and keep different settings per environment.
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
database_url: str
secret_key: str
debug: bool = False
model_config = SettingsConfigDict(env_file=".env")
@lru_cache
def get_settings() -> Settings:
return Settings()
@app.get("/info")
def info(settings: Settings = Depends(get_settings)):
return {"debug": settings.debug}