""" 配置管理模块 从环境变量加载配置 """ import os from pathlib import Path from typing import Optional from pydantic_settings import BaseSettings from functools import lru_cache # 查找.env文件的位置 def find_env_file(): """查找.env文件,支持从backend目录或项目根目录启动""" current_dir = Path.cwd() # 尝试当前目录 env_path = current_dir / ".env" if env_path.exists(): print(f"[Config] 找到.env文件: {env_path}") return str(env_path) # 尝试父目录(项目根目录) env_path = current_dir.parent / ".env" if env_path.exists(): print(f"[Config] 找到.env文件: {env_path}") return str(env_path) # 尝试backend的父目录 if current_dir.name == "backend": env_path = current_dir.parent / ".env" if env_path.exists(): print(f"[Config] 找到.env文件: {env_path}") return str(env_path) # 尝试从环境变量指定的路径 if os.getenv('ENV_FILE'): env_path = Path(os.getenv('ENV_FILE')) if env_path.exists(): print(f"[Config] 从ENV_FILE环境变量找到.env文件: {env_path}") return str(env_path) print(f"[Config] 警告:未找到.env文件,当前目录: {current_dir}") # 默认返回当前目录的.env return ".env" class Settings(BaseSettings): """应用配置""" # Tushare配置 tushare_token: str = "" # 智谱AI配置 zhipuai_api_key: str = "" # 数据库配置 database_url: str = "sqlite:///./stock_agent.db" # API配置 api_host: str = "0.0.0.0" api_port: int = 8000 debug: bool = True # 安全配置 secret_key: str = "change-this-secret-key-in-production" rate_limit: str = "100/minute" # CORS配置 cors_origins: str = "http://localhost:8000,http://127.0.0.1:8000" class Config: env_file = find_env_file() case_sensitive = False @lru_cache() def get_settings() -> Settings: """获取配置单例""" return Settings()