"""配置管理模块 使用 Pydantic Settings 管理环境变量配置 遵循瑞小美系统技术栈标准 """ import os import secrets import warnings from functools import lru_cache from typing import Optional from pydantic_settings import BaseSettings from pydantic import model_validator class Settings(BaseSettings): """应用配置""" # 应用配置 APP_NAME: str = "智能项目定价模型" APP_VERSION: str = "1.0.0" APP_ENV: str = "development" DEBUG: bool = True SECRET_KEY: str = "" # 必须通过环境变量设置 # 数据库配置 - MySQL 8.0, utf8mb4 # 开发环境使用默认值,生产环境必须通过环境变量设置 DATABASE_URL: str = "sqlite+aiosqlite:///:memory:" # 安全的开发默认值 # 数据库连接池配置 DB_POOL_SIZE: int = 5 DB_MAX_OVERFLOW: int = 10 DB_POOL_RECYCLE: int = 3600 # 门户系统配置 - AI Key 从门户获取 PORTAL_CONFIG_API: str = "http://portal-backend:8000/api/ai/internal/config" # AI 服务配置 AI_MODULE_CODE: str = "pricing_model" # 时区配置 - Asia/Shanghai TIMEZONE: str = "Asia/Shanghai" # CORS 配置 - 生产环境应限制为具体域名 CORS_ORIGINS: list[str] = ["http://localhost:5173", "http://127.0.0.1:5173"] # API 配置 API_V1_PREFIX: str = "/api/v1" @model_validator(mode='after') def validate_production_config(self) -> 'Settings': """验证生产环境配置安全性""" if self.APP_ENV == "production": # 生产环境必须设置安全的 SECRET_KEY if not self.SECRET_KEY or self.SECRET_KEY == "your-secret-key-change-in-production": raise ValueError("生产环境必须设置 SECRET_KEY 环境变量") # 生产环境 CORS 不能使用 "*" if "*" in self.CORS_ORIGINS: warnings.warn("生产环境 CORS_ORIGINS 不应使用 '*',请设置具体的允许域名") # 生产环境不应开启 DEBUG if self.DEBUG: warnings.warn("生产环境建议关闭 DEBUG 模式") # 如果没有设置 SECRET_KEY,开发环境自动生成一个 if not self.SECRET_KEY: self.SECRET_KEY = secrets.token_urlsafe(32) return self class Config: env_file = ".env" env_file_encoding = "utf-8" case_sensitive = True @lru_cache() def get_settings() -> Settings: """获取配置单例""" return Settings() settings = get_settings()