59 lines
1.3 KiB
Python
59 lines
1.3 KiB
Python
|
|
"""配置管理模块
|
|||
|
|
|
|||
|
|
从环境变量加载应用配置,使用pydantic-settings进行类型验证
|
|||
|
|
"""
|
|||
|
|
import os
|
|||
|
|
from pathlib import Path
|
|||
|
|
from pydantic_settings import BaseSettings
|
|||
|
|
from functools import lru_cache
|
|||
|
|
from typing import Optional
|
|||
|
|
|
|||
|
|
|
|||
|
|
# 获取项目根目录(config文件夹所在目录)
|
|||
|
|
PROJECT_ROOT = Path(__file__).parent.parent.parent
|
|||
|
|
CONFIG_DIR = PROJECT_ROOT / "config"
|
|||
|
|
|
|||
|
|
|
|||
|
|
class Settings(BaseSettings):
|
|||
|
|
"""应用配置类,从环境变量加载"""
|
|||
|
|
|
|||
|
|
# 数据库配置
|
|||
|
|
database_host: str = "localhost"
|
|||
|
|
database_port: int = 5432
|
|||
|
|
database_name: str = "prostock"
|
|||
|
|
database_user: str
|
|||
|
|
database_password: str
|
|||
|
|
|
|||
|
|
# API密钥配置
|
|||
|
|
api_key: str
|
|||
|
|
secret_key: str
|
|||
|
|
|
|||
|
|
# Redis配置
|
|||
|
|
redis_host: str = "localhost"
|
|||
|
|
redis_port: int = 6379
|
|||
|
|
redis_password: Optional[str] = None
|
|||
|
|
|
|||
|
|
# 应用配置
|
|||
|
|
app_env: str = "development"
|
|||
|
|
app_debug: bool = False
|
|||
|
|
app_port: int = 8000
|
|||
|
|
|
|||
|
|
class Config:
|
|||
|
|
# 从 config/ 目录读取 .env.local 文件
|
|||
|
|
env_file = str(CONFIG_DIR / ".env.local")
|
|||
|
|
env_file_encoding = "utf-8"
|
|||
|
|
case_sensitive = False
|
|||
|
|
|
|||
|
|
|
|||
|
|
@lru_cache()
|
|||
|
|
def get_settings() -> Settings:
|
|||
|
|
"""获取配置单例
|
|||
|
|
|
|||
|
|
使用lru_cache确保配置只加载一次
|
|||
|
|
"""
|
|||
|
|
return Settings()
|
|||
|
|
|
|||
|
|
|
|||
|
|
# 导出配置实例供全局使用
|
|||
|
|
settings = get_settings()
|