template_config_manager.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import json
  2. import os
  3. from typing import Dict, Any, List
  4. class TemplateConfigManager:
  5. def __init__(self, config_path: str = "config/template_config.json"):
  6. self.config_path = config_path
  7. self.config = self._load_config()
  8. def _load_config(self) -> Dict[str, Any]:
  9. """加载配置文件"""
  10. if os.path.exists(self.config_path):
  11. try:
  12. with open(self.config_path, "r", encoding="utf-8") as f:
  13. return json.load(f)
  14. except Exception as e:
  15. print(f"加载配置文件失败: {e}")
  16. return {"template_extensions": {}}
  17. return {"template_extensions": {}}
  18. def get_template_config(self, template_name: str) -> Dict[str, Any]:
  19. """获取指定模板的配置,并过滤空白值"""
  20. template_config = self.config.get("template_extensions", {}).get(
  21. template_name, {}
  22. )
  23. return self._filter_empty_values(template_config)
  24. def _filter_empty_values(self, config: Dict[str, Any]) -> Dict[str, Any]:
  25. """过滤掉空白值(空列表、空字符串等)"""
  26. filtered = {}
  27. for key, value in config.items():
  28. if isinstance(value, dict):
  29. # 递归处理嵌套字典
  30. filtered_subdict = self._filter_empty_values(value)
  31. if filtered_subdict: # 只添加非空的子字典
  32. filtered[key] = filtered_subdict
  33. elif isinstance(value, list):
  34. # 过滤空列表和非空字符串元素
  35. filtered_list = [item for item in value if item and str(item).strip()]
  36. if filtered_list: # 只添加非空列表
  37. filtered[key] = filtered_list
  38. elif isinstance(value, str) and value.strip():
  39. # 只添加非空字符串
  40. filtered[key] = value
  41. elif value: # 其他非空值(数字、布尔值等)
  42. filtered[key] = value
  43. return filtered