| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- from api import recommend_router, report_router, eval_report_router
- from core import get_logger, AppException, RequestLoggingMiddleware, get_request_id
- from database.db.mysql import MySqlDatabaseHelper
- from database.db.redis_db import RedisDatabaseHelper
- from fastapi import FastAPI, Request, status
- from fastapi.exceptions import RequestValidationError
- from fastapi.responses import JSONResponse
- import uvicorn
- logger = get_logger("app")
- app = FastAPI()
- app.add_middleware(RequestLoggingMiddleware)
- @app.exception_handler(RequestValidationError)
- async def validation_exception_handler(request: Request, exc: RequestValidationError):
- logger.warning(f"Validation error: {exc.errors()}")
- return JSONResponse(
- status_code=status.HTTP_400_BAD_REQUEST,
- content={
- "code": 400,
- "msg": "请求参数错误",
- "data": {"detail": exc.errors(), "body": exc.body},
- "request_id": get_request_id(),
- },
- )
- @app.exception_handler(AppException)
- async def app_exception_handler(request: Request, exc: AppException):
- logger.error(f"AppException: {exc.message}", extra={"extra_data": {"detail": exc.detail}})
- return JSONResponse(
- status_code=exc.code,
- content={
- "code": exc.code,
- "msg": exc.message,
- "data": {"detail": exc.detail},
- "request_id": get_request_id(),
- },
- )
- @app.exception_handler(Exception)
- async def unhandled_exception_handler(request: Request, exc: Exception):
- logger.error("Unhandled exception", exc_info=True)
- return JSONResponse(
- status_code=500,
- content={
- "code": 500,
- "msg": "服务器内部错误",
- "data": None,
- "request_id": get_request_id(),
- },
- )
- @app.get("/health")
- async def health_check():
- mysql_ok = False
- redis_ok = False
- try:
- mysql_ok = MySqlDatabaseHelper().check_connection()
- except Exception:
- pass
- try:
- redis_ok = RedisDatabaseHelper().check_connection()
- except Exception:
- pass
- healthy = mysql_ok and redis_ok
- return {
- "status": "healthy" if healthy else "degraded",
- "mysql": "ok" if mysql_ok else "error",
- "redis": "ok" if redis_ok else "error",
- }
- url_prefix = "/brandcultivation/api/v1"
- app.include_router(recommend_router, prefix=url_prefix)
- app.include_router(report_router, prefix=url_prefix)
- app.include_router(eval_report_router, prefix=url_prefix)
- if __name__ == "__main__":
- logger.info("Starting BrandCultivation API server on port 7960")
- uvicorn.run(app, host="0.0.0.0", port=7960)
|