config_proxy.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from fastapi import APIRouter, HTTPException, Body, status
  2. from fastapi.responses import JSONResponse
  3. import httpx
  4. from ..core.logger import get_logger
  5. from ..core.config import settings
  6. logger = get_logger(__name__)
  7. router = APIRouter()
  8. @router.get("/scoring_config", summary="[代理] 获取评分配置")
  9. async def proxy_get_scoring_config():
  10. """
  11. 转发请求到分数的获取配置接口
  12. """
  13. target_url = settings.SCORE_SERVER_CONFIG_URL
  14. logger.info(f"正在代理 GET 请求到: {target_url}")
  15. async with httpx.AsyncClient() as client:
  16. try:
  17. # 发送请求给项目1
  18. resp = await client.get(target_url, timeout=10.0)
  19. # 如果项目1返回错误状态码,抛出对应的 HTTPException
  20. if resp.status_code != 200:
  21. logger.error(f"项目1返回错误: {resp.status_code} - {resp.text}")
  22. raise HTTPException(
  23. status_code=resp.status_code,
  24. detail=resp.json().get("detail", "上游服务错误")
  25. )
  26. # 返回项目1的数据
  27. return resp.json()
  28. except httpx.RequestError as exc:
  29. logger.error(f"连接项目1失败: {exc}")
  30. raise HTTPException(
  31. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  32. detail=f"无法连接到评分服务 (Project 1): {exc}"
  33. )
  34. @router.put("/scoring_config", summary="[代理] 更新评分配置")
  35. async def proxy_update_scoring_config(config_data: dict = Body(...)):
  36. """
  37. 转发请求到分数的更新配置接口
  38. """
  39. target_url = settings.SCORE_SERVER_CONFIG_URL
  40. logger.info(f"正在代理 PUT 请求到: {target_url}")
  41. async with httpx.AsyncClient() as client:
  42. try:
  43. # 将前端传来的 json 原封不动转发给项目1
  44. resp = await client.put(target_url, json=config_data, timeout=10.0)
  45. # 处理项目1的响应
  46. if resp.status_code != 200:
  47. # 可能是 400 校验错误,或者是 500 内部错误
  48. error_detail = "上游服务错误"
  49. try:
  50. error_detail = resp.json().get("detail", error_detail)
  51. except:
  52. pass
  53. logger.warning(f"项目1拒绝更新: {resp.status_code} - {error_detail}")
  54. raise HTTPException(
  55. status_code=resp.status_code,
  56. detail=error_detail
  57. )
  58. return JSONResponse(
  59. status_code=resp.status_code,
  60. content=resp.json()
  61. )
  62. except httpx.RequestError as exc:
  63. logger.error(f"连接项目1失败: {exc}")
  64. raise HTTPException(
  65. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  66. detail=f"无法连接到评分服务 (Project 1): {exc}"
  67. )