背景简介
在现代应用开发中,统一管理应用程序配置是确保代码可维护性和环境切换便利性的关键。本文介绍的配置管理模块采用 Pydantic 的 BaseSettings 来构建,提供了一种类型安全、环境变量自动加载的优雅解决方案,特别适用于需要支持多环境配置的 Python Web 应用。
前置信息
- Python 后端
详细信息
依赖库
pydantic-settings
- 代码详情
# app/core/config.py
"""Application settings configuration module.
This module defines the Settings class for managing application configuration
using Pydantic BaseSettings. It loads configuration from environment variables
and a .env file located in the project root directory.
"""
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Application settings configuration class.
This class manages all application configuration settings, including
basic app information and database configuration. It automatically
loads settings from environment variables and a `.env` file located
in the project's current working directory.
"""
# --- Basic Configuration ---
ENV_NAME: str #: The name of the environment (e.g., 'development', 'production').
APP_NAME: str = "Personal Website Backend Service" #: The name of the application.
VERSION: str = "1.0.0" #: The version of the application.
DEBUG: bool = True #: A flag to enable or disable debug mode.
# --- User settings ---
DEFAULT_USER_TIMEOUT: int = 60 * 60 # Default expire seconds
# --- API setttings ---
API_V1_STR: str = "/api/v1" # API version
SUCCESS_CODE: int = 0 # Success code
SERVER_ERROR_CODE: int = 1 # Server internal error code
STOP_REGISTER_STR: str = 'True'
# Logging Configuration
LOG_LEVEL: str = "INFO"
LOG_FORMAT: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
# --- JWT settings ---
SECRET_KEY: str
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 # Token expired after 1 hour
ALGORITHM: str = "HS256" # Encrypt algorithm with HS256
# --- Database Configuration ---
DATABASE_URL: str #: The database connection URL.
DB_ECHO: bool
# redis settings
REDIS_URL: str # Async Redis connection url from .env file
SYNC_REDIS_URL: str # Sync redis connection url from .env file
# zhipu ai
CHATGLM_APIKEY: str
CHATGLM_MODEL: str
CHATGLM_APIBASE: str
# --- celery ---
CELERY_BROKER_URL: str
CELERY_RESULT_BACKEND: str
# --- CORS ---
CORS_DOMAIN_STR: str
model_config = SettingsConfigDict(
env_file="./.env",
env_file_encoding="utf-8",
extra="ignore",
case_sensitive=False
)
# Global settings instance
settings = Settings()
该配置模块定义了一个 Settings 类,继承自 BaseSettings,主要特点包括:
-
自动配置加载:自动从项目根目录的
.env文件和环境变量中加载配置 -
类型安全:所有配置项都有明确的类型注解,Pydantic 会自动进行类型验证
-
配置分类:
- 基础配置:环境名、应用名称、版本、调试模式
- 用户设置:默认用户超时时间
- API 设置:版本路径、状态码、注册开关
- 日志配置:日志级别和格式
- JWT 设置:密钥、过期时间、加密算法
- 数据库配置:数据库连接 URL、SQL 日志开关
- Redis 配置:异步和同步连接 URL
- 智谱 AI 配置:API 密钥、模型名称和 API 基础路径
- Celery 配置:消息代理和结果后端
- CORS 配置:允许的域名
-
全局实例:模块底部创建了
settings全局实例,方便在整个应用中导入使用 -
配置选项:支持忽略额外环境变量、不区分大小写等特性
这种配置管理方式简洁高效,特别适合需要支持多环境部署的 Python 项目。
以上便是本文的全部内容,感谢您的阅读,如遇到任何问题,欢迎在评论区留言讨论。