config_loader.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import yaml
  2. import os
  3. from urllib.parse import urljoin
  4. from core.utils.path_utils import config_spiders_path
  5. class ConfigLoader:
  6. _config = None
  7. _config_path = config_spiders_path
  8. @classmethod
  9. def _load_yaml(cls):
  10. if not os.path.exists(cls._config_path):
  11. raise FileNotFoundError(f"[配置错误] 找不到配置文件: {cls._config_path}")
  12. with open(cls._config_path, "r", encoding="utf-8") as f:
  13. cls._config = yaml.safe_load(f)
  14. @classmethod
  15. def get_platform_config(cls, platform: str) -> dict:
  16. """
  17. 获取平台配置,并拼接完整 URL
  18. 支持类方法调用 + 单次加载配置
  19. """
  20. if cls._config is None:
  21. cls._load_yaml()
  22. if platform not in cls._config:
  23. raise ValueError(f"[配置错误] 未找到平台配置: {platform}")
  24. platform_config = cls._config.get(platform, {})
  25. base_config = cls._config.get("default", {})
  26. # 合并配置:平台配置覆盖默认配置
  27. merged = {**base_config, **platform_config}
  28. # 自动拼接完整 url(优先用完整 url)
  29. if "url" not in merged and "base_url" in merged and "path" in merged:
  30. merged["url"] = urljoin(merged["base_url"], merged["path"])
  31. return merged
  32. # 示例使用
  33. if __name__ == '__main__':
  34. config = ConfigLoader.get_platform_config("benshanzhufu")
  35. print(config)