示例工程 37-config-pydantic-settings

37-config-pydantic-settings/04-precedence/precedence.py

python · 1.2 KB

"""配置来源优先级:显式参数 > 环境变量 > .env > 默认值。"""
 
from __future__ import annotations
 
from collections.abc import Mapping
 
from pydantic import BaseModel
 
 
class Settings(BaseModel):
    host: str = "localhost"
    port: int = 8000
    debug: bool = False
 
 
def normalize(mapping: Mapping[str, object]) -> dict[str, object]:
    return {str(key).lower().removeprefix("app_"): value for key, value in mapping.items()}
 
 
def resolve(
    env: Mapping[str, str],
    dotenv: Mapping[str, str],
    explicit: Mapping[str, object],
) -> Settings:
    merged: dict[str, object] = {"host": "localhost", "port": 8000, "debug": False}
    merged.update(normalize(dotenv))
    merged.update(normalize(env))
    merged.update(normalize(explicit))
    return Settings.model_validate(merged)
 
 
def main() -> None:
    settings = resolve(
        env={"APP_HOST": "env-host", "APP_PORT": "9000"},
        dotenv={"APP_HOST": "dotenv-host", "APP_PORT": "7000", "APP_DEBUG": "true"},
        explicit={"APP_HOST": "explicit-host"},
    )
    print(f"host: {settings.host}")
    print(f"port: {settings.port}")
    print(f"debug: {settings.debug}")
 
 
if __name__ == "__main__":
    main()