config_proxy.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. from contextlib import asynccontextmanager
  7. logger = get_logger(__name__)
  8. router = APIRouter()
  9. # 1. 创建一个全局的 client (配置好超时和连接池)
  10. # limits: max_keepalive_connections 控制连接池大小
  11. http_client = httpx.AsyncClient(timeout=10.0, limits=httpx.Limits(max_keepalive_connections=20, max_connections=100))
  12. @router.get("/scoring_config", summary="[代理] 获取评分配置")
  13. async def proxy_get_scoring_config():
  14. target_url = settings.SCORE_SERVER_CONFIG_URL
  15. try:
  16. # 2. 直接使用全局 client,不需要 async with
  17. resp = await http_client.get(target_url)
  18. if resp.status_code != 200:
  19. logger.error(f"项目1返回错误: {resp.status_code} - {resp.text}")
  20. raise HTTPException(
  21. status_code=resp.status_code,
  22. detail=resp.json().get("detail", "上游服务错误")
  23. )
  24. return resp.json()
  25. except httpx.RequestError as exc:
  26. logger.error(f"连接项目1失败: {exc}")
  27. raise HTTPException(status_code=503, detail=str(exc))
  28. @router.put("/scoring_config", summary="[代理] 更新评分配置")
  29. async def proxy_update_scoring_config(config_data: dict = Body(...)):
  30. target_url = settings.SCORE_SERVER_CONFIG_URL
  31. try:
  32. # 2. 复用连接
  33. resp = await http_client.put(target_url, json=config_data)
  34. if resp.status_code != 200:
  35. raise HTTPException(status_code=resp.status_code, detail=f"保存失败: {resp.json()['detail']}")
  36. return_data = {"detail": f"{resp.json()['message']}"}
  37. return JSONResponse(status_code=resp.status_code, content=return_data)
  38. except httpx.RequestError as exc:
  39. logger.error(f"连接项目1失败: {exc}")
  40. raise HTTPException(status_code=503, detail=str(exc))