from dataclasses import dataclass import toml @dataclass class DatabaseConfig: """数据库配置""" host: str port: int user: str password: str database: str @dataclass class ChromeConfig: """浏览器配置""" proxy: str browser_path: str @dataclass class AppConfig: """总配置,如果未来增加 Web 服务,添加 WebConfig 即可""" debug: bool wap_screenshot: bool headless_chrome: bool database: DatabaseConfig chrome: ChromeConfig def load_config(config_path: str) -> AppConfig: """加载配置""" with open(config_path, "r", encoding="utf-8") as f: config_dict = toml.load(f) database_config = DatabaseConfig(**config_dict["database"]) chrome_config = ChromeConfig(**config_dict["chrome"]) AppCtx.g_app_config = AppConfig( debug=config_dict["debug"], wap_screenshot=config_dict["wap_screenshot"], headless_chrome=True, database=database_config, chrome=chrome_config ) return AppCtx.g_app_config class AppCtx: # 全局变量 # 配置信息 g_app_config: AppConfig = None # 数据库连接 g_db_engine = None