Files
ccdi/lsfx-mock-server/utils/response_builder.py

70 lines
2.0 KiB
Python
Raw Normal View History

import json
from pathlib import Path
from typing import Dict, Any
import copy
class ResponseBuilder:
"""响应构建器"""
TEMPLATE_DIR = Path(__file__).parent.parent / "config" / "responses"
@staticmethod
def load_template(template_name: str) -> Dict:
"""加载 JSON 模板
Args:
template_name: 模板名称不含.json扩展名
Returns:
模板字典
"""
file_path = ResponseBuilder.TEMPLATE_DIR / f"{template_name}.json"
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
@staticmethod
def replace_placeholders(template: Dict, **kwargs) -> Dict:
"""递归替换占位符
Args:
template: 模板字典
**kwargs: 占位符键值对
Returns:
替换后的字典
"""
def replace_value(value):
if isinstance(value, str):
result = value
for key, val in kwargs.items():
placeholder = f"{{{key}}}"
if placeholder in result:
result = result.replace(placeholder, str(val))
return result
elif isinstance(value, dict):
return {k: replace_value(v) for k, v in value.items()}
elif isinstance(value, list):
return [replace_value(item) for item in value]
return value
# 深拷贝模板,避免修改原始数据
return replace_value(copy.deepcopy(template))
@staticmethod
def build_success_response(template_name: str, **kwargs) -> Dict:
"""构建成功响应
Args:
template_name: 模板名称
**kwargs: 占位符键值对
Returns:
响应字典
"""
template = ResponseBuilder.load_template(template_name)
return ResponseBuilder.replace_placeholders(
template["success_response"],
**kwargs
)