""" 配置管理工具类 支持读取、修改和保存 YAML 配置文件 """ import os from pathlib import Path from typing import Any, Dict, Optional, Union import yaml class Config: """ 配置管理类 功能: - 读取 YAML 配置文件 - 支持嵌套键访问(如 'database.host') - 修改配置值 - 保存配置到文件 - 合并多个配置文件(全局配置 + 环境配置) """ def __init__(self, config_file: Optional[Union[str, Path]] = None): """ 初始化配置对象 Args: config_file: 配置文件路径,支持相对路径和绝对路径 如果为 None,从环境变量 CONFIG_FILE 读取 """ self._data: Dict[str, Any] = {} self._config_file: Optional[Path] = None if config_file is None: # 从环境变量读取 config_file = os.environ.get("CONFIG_FILE") if config_file: self.load(config_file) def load(self, config_file: Union[str, Path], merge: bool = False) -> "Config": """ 加载配置文件 Args: config_file: 配置文件路径 merge: 是否合并到现有配置(True)还是覆盖(False) Returns: self,支持链式调用 """ config_path = Path(config_file) # 如果是相对路径,相对于项目根目录 if not config_path.is_absolute(): project_root = Path(__file__).parent.parent.parent config_path = project_root / config_path if not config_path.exists(): raise FileNotFoundError(f"配置文件不存在: {config_path}") with open(config_path, "r", encoding="utf-8") as f: data = yaml.safe_load(f) or {} if merge: self._merge_dict(self._data, data) else: self._data = data self._config_file = config_path return self def load_with_global(self, env_config: Union[str, Path]) -> "Config": """ 加载环境配置并合并全局配置 Args: env_config: 环境配置文件(如 'configs/production.yaml') Returns: self,支持链式调用 """ # 先加载全局配置 self.load("configs/global.yaml") # 再加载环境配置并合并 self.load(env_config, merge=True) return self def get(self, key: str, default: Any = None) -> Any: """ 获取配置值,支持嵌套键 Args: key: 配置键,支持点分隔的嵌套键(如 'database.host') default: 默认值 Returns: 配置值 Examples: >>> config.get('app.name') 'QTrade' >>> config.get('database.host') '127.0.0.1' """ keys = key.split(".") value = self._data for k in keys: if isinstance(value, dict): value = value.get(k) else: return default if value is None: return default return value def set(self, key: str, value: Any) -> "Config": """ 设置配置值,支持嵌套键 Args: key: 配置键,支持点分隔的嵌套键 value: 配置值 Returns: self,支持链式调用 Examples: >>> config.set('database.host', '192.168.1.100') >>> config.set('app.debug', True) """ keys = key.split(".") data = self._data # 遍历到倒数第二个键 for k in keys[:-1]: if k not in data: data[k] = {} elif not isinstance(data[k], dict): data[k] = {} data = data[k] # 设置最后一个键的值 data[keys[-1]] = value return self def update(self, data: Dict[str, Any]) -> "Config": """ 批量更新配置 Args: data: 配置字典 Returns: self,支持链式调用 Examples: >>> config.update({ ... 'database.host': '192.168.1.100', ... 'database.port': 3307 ... }) """ for key, value in data.items(): self.set(key, value) return self def save(self, config_file: Optional[Union[str, Path]] = None) -> "Config": """ 保存配置到文件 Args: config_file: 配置文件路径,如果为 None,保存到原文件 Returns: self,支持链式调用 """ if config_file is None: config_file = self._config_file if config_file is None: raise ValueError("未指定配置文件路径") config_path = Path(config_file) # 确保目录存在 config_path.parent.mkdir(parents=True, exist_ok=True) with open(config_path, "w", encoding="utf-8") as f: yaml.safe_dump( self._data, f, allow_unicode=True, default_flow_style=False, sort_keys=False, ) return self def to_dict(self) -> Dict[str, Any]: """ 返回配置字典 Returns: 配置字典的副本 """ return self._data.copy() def __getitem__(self, key: str) -> Any: """支持字典式访问""" value = self.get(key) if value is None: raise KeyError(f"配置键不存在: {key}") return value def __setitem__(self, key: str, value: Any) -> None: """支持字典式赋值""" self.set(key, value) def __contains__(self, key: str) -> bool: """支持 in 操作""" return self.get(key) is not None def __repr__(self) -> str: return f"Config(file={self._config_file}, keys={len(self._data)})" @staticmethod def _merge_dict(base: Dict, override: Dict) -> None: """ 递归合并字典(原地修改 base) Args: base: 基础字典 override: 覆盖字典 """ for key, value in override.items(): if key in base and isinstance(base[key], dict) and isinstance(value, dict): Config._merge_dict(base[key], value) else: base[key] = value # 全局配置实例 _global_config: Optional[Config] = None def get_config() -> Config: """ 获取全局配置实例(单例模式) Returns: 全局配置对象 Examples: >>> from src.core.config import get_config >>> config = get_config() >>> db_host = config.get('database.host') """ global _global_config if _global_config is None: # 从环境变量读取配置文件 config_file = os.environ.get("CONFIG_FILE") if config_file: _global_config = Config().load_with_global(config_file) else: # 默认加载全局配置 _global_config = Config("configs/global.yaml") return _global_config def set_config(config: Config) -> None: """ 设置全局配置实例 Args: config: 配置对象 """ global _global_config _global_config = config