run_api.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. from api import recommend_router, report_router, eval_report_router
  2. from core import get_logger, AppException, RequestLoggingMiddleware, get_request_id
  3. from database.db.mysql import MySqlDatabaseHelper
  4. from database.db.redis_db import RedisDatabaseHelper
  5. from fastapi import FastAPI, Request, status
  6. from fastapi.exceptions import RequestValidationError
  7. from fastapi.responses import JSONResponse
  8. import uvicorn
  9. logger = get_logger("app")
  10. app = FastAPI()
  11. app.add_middleware(RequestLoggingMiddleware)
  12. @app.exception_handler(RequestValidationError)
  13. async def validation_exception_handler(request: Request, exc: RequestValidationError):
  14. logger.warning(f"Validation error: {exc.errors()}")
  15. return JSONResponse(
  16. status_code=status.HTTP_400_BAD_REQUEST,
  17. content={
  18. "code": 400,
  19. "msg": "请求参数错误",
  20. "data": {"detail": exc.errors(), "body": exc.body},
  21. "request_id": get_request_id(),
  22. },
  23. )
  24. @app.exception_handler(AppException)
  25. async def app_exception_handler(request: Request, exc: AppException):
  26. logger.error(f"AppException: {exc.message}", extra={"extra_data": {"detail": exc.detail}})
  27. return JSONResponse(
  28. status_code=exc.code,
  29. content={
  30. "code": exc.code,
  31. "msg": exc.message,
  32. "data": {"detail": exc.detail},
  33. "request_id": get_request_id(),
  34. },
  35. )
  36. @app.exception_handler(Exception)
  37. async def unhandled_exception_handler(request: Request, exc: Exception):
  38. logger.error("Unhandled exception", exc_info=True)
  39. return JSONResponse(
  40. status_code=500,
  41. content={
  42. "code": 500,
  43. "msg": "服务器内部错误",
  44. "data": None,
  45. "request_id": get_request_id(),
  46. },
  47. )
  48. @app.get("/health")
  49. async def health_check():
  50. mysql_ok = False
  51. redis_ok = False
  52. try:
  53. mysql_ok = MySqlDatabaseHelper().check_connection()
  54. except Exception:
  55. pass
  56. try:
  57. redis_ok = RedisDatabaseHelper().check_connection()
  58. except Exception:
  59. pass
  60. healthy = mysql_ok and redis_ok
  61. return {
  62. "status": "healthy" if healthy else "degraded",
  63. "mysql": "ok" if mysql_ok else "error",
  64. "redis": "ok" if redis_ok else "error",
  65. }
  66. url_prefix = "/brandcultivation/api/v1"
  67. app.include_router(recommend_router, prefix=url_prefix)
  68. app.include_router(report_router, prefix=url_prefix)
  69. app.include_router(eval_report_router, prefix=url_prefix)
  70. if __name__ == "__main__":
  71. logger.info("Starting BrandCultivation API server on port 7960")
  72. uvicorn.run(app, host="0.0.0.0", port=7960)