""" 配置管理模块 支持多环境配置切换: - TEST_ENV=local 使用本地配置(默认) - TEST_ENV=remote 使用远程配置 """ import os from pathlib import Path from typing import Any, Optional import yaml class Settings: """配置管理器""" _instance: Optional['Settings'] = None _config: dict = {} def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance._load_config() return cls._instance def _load_config(self): """加载配置文件""" env = os.getenv("TEST_ENV", "local") config_dir = Path(__file__).parent config_file = config_dir / f"{env}.yaml" if not config_file.exists(): raise FileNotFoundError(f"配置文件不存在: {config_file}") with open(config_file, "r", encoding="utf-8") as f: self._config = yaml.safe_load(f) print(f"[配置] 已加载 {env} 环境配置") def get(self, key: str, default: Any = None) -> Any: """ 获取配置值,支持点号分隔的路径 示例: settings.get("api.base_url") settings.get("database.host") """ keys = key.split(".") value = self._config for k in keys: if isinstance(value, dict): value = value.get(k) else: return default if value is None: return default return value @property def api_base_url(self) -> str: return self.get("api.base_url", "http://localhost:3000") @property def api_timeout(self) -> int: return self.get("api.timeout", 30) @property def db_config(self) -> dict: return { "host": self.get("database.host", "localhost"), "port": self.get("database.port", 5432), "database": self.get("database.name", "junhong_dev"), "user": self.get("database.user", "postgres"), "password": self.get("database.password", "postgres"), } @property def redis_config(self) -> dict: return { "host": self.get("redis.host", "localhost"), "port": self.get("redis.port", 6379), "db": self.get("redis.db", 0), } def get_account(self, role: str) -> dict: """获取预置账号信息""" return self.get(f"accounts.{role}", {}) # 全局配置实例 settings = Settings()