|
|
@@ -0,0 +1,129 @@
|
|
|
+from fastapi import APIRouter, File, Body, HTTPException, status
|
|
|
+from fastapi.responses import FileResponse, JSONResponse
|
|
|
+from ..core.config import settings
|
|
|
+import json
|
|
|
+from app.core.logger import get_logger
|
|
|
+
|
|
|
+logger = get_logger(__name__)
|
|
|
+
|
|
|
+router = APIRouter(tags=["Config"])
|
|
|
+
|
|
|
+
|
|
|
+def compare_json_structure(template: dict, data: dict, path: str = "") -> (bool, str):
|
|
|
+ """
|
|
|
+ 递归比较两个字典的结构(键),忽略值。
|
|
|
+ 如果结构不匹配,返回 False 和错误原因。
|
|
|
+ :param template: 模板字典(原始配置)
|
|
|
+ :param data: 新的字典(待验证的配置)
|
|
|
+ :param path: 用于错误报告的当前递归路径
|
|
|
+ :return: 一个元组 (is_match: bool, reason: str)
|
|
|
+ """
|
|
|
+ template_keys = set(template.keys())
|
|
|
+ data_keys = set(data.keys())
|
|
|
+
|
|
|
+ # 检查当前层的键是否完全匹配
|
|
|
+ if template_keys != data_keys:
|
|
|
+ missing_keys = template_keys - data_keys
|
|
|
+ extra_keys = data_keys - template_keys
|
|
|
+ error_msg = f"结构不匹配。在路径 '{path or 'root'}' "
|
|
|
+ if missing_keys:
|
|
|
+ error_msg += f"缺少字段: {missing_keys}。"
|
|
|
+ if extra_keys:
|
|
|
+ error_msg += f"存在多余字段: {extra_keys}。"
|
|
|
+ return False, error_msg
|
|
|
+
|
|
|
+ # 递归检查所有子字典
|
|
|
+ for key in template_keys:
|
|
|
+ if isinstance(template[key], dict) and isinstance(data[key], dict):
|
|
|
+ # 如果两个值都是字典,则递归深入
|
|
|
+ is_match, reason = compare_json_structure(template[key], data[key], path=f"{path}.{key}" if path else key)
|
|
|
+ if not is_match:
|
|
|
+ return False, reason
|
|
|
+ elif isinstance(template[key], dict) or isinstance(data[key], dict):
|
|
|
+ # 如果只有一个是字典,说明结构已改变(例如,一个对象被替换成了字符串)
|
|
|
+ current_path = f"{path}.{key}" if path else key
|
|
|
+ return False, f"结构不匹配。字段 '{current_path}' 的类型已从字典变为非字典(或反之)。"
|
|
|
+
|
|
|
+ return True, "结构匹配"
|
|
|
+
|
|
|
+
|
|
|
+@router.get("/scoring_config", summary="获取评分配置")
|
|
|
+async def get_scoring_config():
|
|
|
+ """
|
|
|
+ 读取并返回 scoring_config.json 文件的内容。
|
|
|
+ """
|
|
|
+ if not settings.SCORE_CONFIG_PATH.exists():
|
|
|
+ logger.error(f"评分配置文件未找到: {settings.SCORE_CONFIG_PATH}")
|
|
|
+ raise HTTPException(
|
|
|
+ status_code=status.HTTP_404_NOT_FOUND,
|
|
|
+ detail="评分配置文件未找到"
|
|
|
+ )
|
|
|
+
|
|
|
+ try:
|
|
|
+ with open(settings.SCORE_CONFIG_PATH, 'r', encoding='utf-8') as f:
|
|
|
+ config_data = json.load(f)
|
|
|
+ return config_data
|
|
|
+ except json.JSONDecodeError:
|
|
|
+ logger.error(f"评分配置文件格式错误,无法解析: {settings.SCORE_CONFIG_PATH}")
|
|
|
+ raise HTTPException(
|
|
|
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
+ detail="评分配置文件格式错误"
|
|
|
+ )
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"读取配置文件时发生未知错误: {e}")
|
|
|
+ raise HTTPException(
|
|
|
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
+ detail=f"读取配置文件时发生未知错误: {e}"
|
|
|
+ )
|
|
|
+
|
|
|
+
|
|
|
+@router.put("/scoring_config", summary="更新评分配置")
|
|
|
+async def update_scoring_config(new_config: dict = Body(...)):
|
|
|
+ """
|
|
|
+ 接收新的JSON配置,验证其结构与现有配置完全一致后,覆盖保存。
|
|
|
+ 只允许修改值,不允许增、删、改任何字段名。
|
|
|
+ """
|
|
|
+ # 1. 检查并读取当前的配置文件作为模板
|
|
|
+ if not settings.SCORE_CONFIG_PATH.exists():
|
|
|
+ logger.error(f"尝试更新一个不存在的配置文件: {settings.SCORE_CONFIG_PATH}")
|
|
|
+ raise HTTPException(
|
|
|
+ status_code=status.HTTP_404_NOT_FOUND,
|
|
|
+ detail="无法更新,因为原始配置文件未找到"
|
|
|
+ )
|
|
|
+
|
|
|
+ try:
|
|
|
+ with open(settings.SCORE_CONFIG_PATH, 'r', encoding='utf-8') as f:
|
|
|
+ current_config = json.load(f)
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"更新前读取原始配置文件失败: {e}")
|
|
|
+ raise HTTPException(
|
|
|
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
+ detail=f"读取原始配置文件失败: {e}"
|
|
|
+ )
|
|
|
+
|
|
|
+ # 2. 比较新旧配置的结构
|
|
|
+ is_valid, reason = compare_json_structure(current_config, new_config)
|
|
|
+
|
|
|
+ if not is_valid:
|
|
|
+ logger.warning(f"更新评分配置失败,结构校验未通过: {reason}")
|
|
|
+ raise HTTPException(
|
|
|
+ status_code=status.HTTP_400_BAD_REQUEST,
|
|
|
+ detail=f"配置更新失败。{reason} 请确保只修改数值,不要添加、删除或重命名字段。"
|
|
|
+ )
|
|
|
+
|
|
|
+ # 3. 结构验证通过,写入新文件
|
|
|
+ try:
|
|
|
+ with open(settings.SCORE_CONFIG_PATH, 'w', encoding='utf-8') as f:
|
|
|
+ # 使用 indent=2 格式化输出,方便人工阅读
|
|
|
+ json.dump(new_config, f, indent=2, ensure_ascii=False)
|
|
|
+ logger.info("评分配置文件已成功更新。")
|
|
|
+ return JSONResponse(
|
|
|
+ status_code=status.HTTP_200_OK,
|
|
|
+ content={"message": "配置已成功更新"}
|
|
|
+ )
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"写入新配置文件时发生错误: {e}")
|
|
|
+ raise HTTPException(
|
|
|
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
+ detail=f"保存新配置文件时发生错误: {e}"
|
|
|
+ )
|