main.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """
  2. FastAPI应用入口 - 技术框架
  3. 增强功能:API接口日志记录,记录入参密文、入参明文、出参明文、出参密文
  4. """
  5. from fastapi import FastAPI, Request
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from fastapi.responses import JSONResponse
  8. from app.core.logger import setup_logger
  9. from app.utils.exceptions import BusinessException
  10. # 设置日志
  11. logger = setup_logger()
  12. # 创建FastAPI应用
  13. app = FastAPI(
  14. title="游铛铛客户端API",
  15. description="游铛铛产品客户端技术框架 - 增强API日志记录功能",
  16. version="1.0.0",
  17. docs_url="/docs",
  18. redoc_url="/redoc",
  19. )
  20. # CORS配置
  21. app.add_middleware(
  22. CORSMiddleware,
  23. allow_origins=["*"],
  24. allow_credentials=True,
  25. allow_methods=["*"],
  26. allow_headers=["*"],
  27. )
  28. # 添加增强的API日志中间件(记录入参出参的明文和密文)
  29. from app.middleware.logging import APILoggingASGIMiddleware
  30. app.add_middleware(APILoggingASGIMiddleware)
  31. # 异常处理
  32. from fastapi import HTTPException
  33. @app.exception_handler(HTTPException)
  34. async def http_exception_handler(request: Request, exc: HTTPException):
  35. """统一处理HTTPException,返回前端期望的格式"""
  36. return JSONResponse(
  37. status_code=exc.status_code,
  38. content={"code": exc.status_code, "msg": exc.detail}
  39. )
  40. @app.exception_handler(BusinessException)
  41. async def business_exception_handler(request: Request, exc: BusinessException):
  42. return JSONResponse(
  43. status_code=200,
  44. content={"code": exc.code, "msg": exc.msg}
  45. )
  46. @app.exception_handler(Exception)
  47. async def general_exception_handler(request: Request, exc: Exception):
  48. logger.error("未处理的异常", exc_info=True)
  49. return JSONResponse(
  50. status_code=500,
  51. content={"code": 500, "msg": "服务器内部错误"}
  52. )
  53. @app.get("/")
  54. async def root():
  55. """根路径"""
  56. return {"message": "游铛铛客户端API", "version": "1.0.0"}
  57. @app.get("/health")
  58. async def health():
  59. """健康检查"""
  60. return {"status": "ok"}
  61. # 注册API路由
  62. from app.api import api_router
  63. app.include_router(api_router, prefix="/api")
  64. if __name__ == "__main__":
  65. import uvicorn
  66. uvicorn.run(app, host="0.0.0.0", port=9000)