| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- import json
- import os
- from typing import Dict, Any, List
- class TemplateConfigManager:
- def __init__(self, config_path: str = "config/template_config.json"):
- self.config_path = config_path
- self.config = self._load_config()
- def _load_config(self) -> Dict[str, Any]:
- """加载配置文件"""
- if os.path.exists(self.config_path):
- try:
- with open(self.config_path, "r", encoding="utf-8") as f:
- return json.load(f)
- except Exception as e:
- print(f"加载配置文件失败: {e}")
- return {"template_extensions": {}}
- return {"template_extensions": {}}
- def get_template_config(self, template_name: str) -> Dict[str, Any]:
- """获取指定模板的配置,并过滤空白值"""
- template_config = self.config.get("template_extensions", {}).get(
- template_name, {}
- )
- return self._filter_empty_values(template_config)
- def _filter_empty_values(self, config: Dict[str, Any]) -> Dict[str, Any]:
- """过滤掉空白值(空列表、空字符串等)"""
- filtered = {}
- for key, value in config.items():
- if isinstance(value, dict):
- # 递归处理嵌套字典
- filtered_subdict = self._filter_empty_values(value)
- if filtered_subdict: # 只添加非空的子字典
- filtered[key] = filtered_subdict
- elif isinstance(value, list):
- # 过滤空列表和非空字符串元素
- filtered_list = [item for item in value if item and str(item).strip()]
- if filtered_list: # 只添加非空列表
- filtered[key] = filtered_list
- elif isinstance(value, str) and value.strip():
- # 只添加非空字符串
- filtered[key] = value
- elif value: # 其他非空值(数字、布尔值等)
- filtered[key] = value
- return filtered
|