""" 配置管理模块 支持多配置项、默认值回退、自动保存 """ import json import os import logging logger = logging.getLogger(__name__) CONFIG_FILE = "config.json" OUTPUT_DIR = "xhs_workspace" DEFAULT_CONFIG = { "api_key": "", "base_url": "https://api.openai.com/v1", "sd_url": "http://127.0.0.1:7860", "mcp_url": "http://localhost:18060/mcp", "model": "gpt-3.5-turbo", "persona": "温柔知性的时尚博主", "auto_reply_enabled": False, "schedule_enabled": False, } class ConfigManager: """配置管理器 - 单例模式""" _instance = None _config = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self): if self._config is None: self._config = self._load() def _load(self) -> dict: """从文件加载配置,缺失项用默认值填充""" config = DEFAULT_CONFIG.copy() if os.path.exists(CONFIG_FILE): try: with open(CONFIG_FILE, "r", encoding="utf-8") as f: saved = json.load(f) config.update(saved) except (json.JSONDecodeError, IOError) as e: logger.warning("配置文件读取失败,使用默认值: %s", e) return config def save(self): """保存配置到文件""" try: with open(CONFIG_FILE, "w", encoding="utf-8") as f: json.dump(self._config, f, indent=4, ensure_ascii=False) except IOError as e: logger.error("配置保存失败: %s", e) def get(self, key: str, default=None): """获取配置项""" return self._config.get(key, default) def set(self, key: str, value): """设置配置项并自动保存""" self._config[key] = value self.save() def update(self, data: dict): """批量更新配置""" self._config.update(data) self.save() @property def all(self) -> dict: """返回全部配置(副本)""" return self._config.copy() def ensure_workspace(self): """确保工作空间目录存在""" os.makedirs(OUTPUT_DIR, exist_ok=True)