设置 config.py

发布: (2026年4月6日 GMT+8 00:13)
1 分钟阅读
原文: Dev.to

Source: Dev.to

安装

pip install pydantic-settings

config.py

from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    APP_ENV: str = "development"
    APP_TITLE: str = "App Title"
    APP_VERSION: str = "1.0.0"
    FRONTEND_URL: str = "http://localhost:5173"
    SECRET_KEY: str
    CORS_ORIGINS: list[str] = []

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = True
        extra = "ignore"

settings = Settings()

为什么这实际上很好

  • 你拥有 默认值,因此应用可以立即运行。
  • 你拥有 环境覆盖,生产环境不会出错。
  • 你拥有 类型安全,以后不会出现奇怪的 bug。

如何使用

import config.settings

print(settings.APP_ENV)
0 浏览
Back to Blog

相关文章

阅读更多 »