main.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """
  2. FastAPI应用入口 - 管理端接口服务
  3. """
  4. from fastapi import FastAPI, Request
  5. from fastapi.middleware.cors import CORSMiddleware
  6. from fastapi.responses import JSONResponse
  7. from app.api.admin import router as admin_router
  8. from app.core.logger import setup_logger
  9. from app.utils.exceptions import BusinessException
  10. from app.background_tasks import lifespan_manager
  11. from app.core.config_cache import config_cache
  12. # 设置日志
  13. logger = setup_logger()
  14. # 启动时加载配置
  15. logger.info("启动时加载系统配置...")
  16. config_cache.load_configs()
  17. logger.info(f"系统配置加载完成,共 {len(config_cache.get_all())} 项配置")
  18. # 创建FastAPI应用
  19. app = FastAPI(
  20. title="游铛铛管理端API",
  21. description="游铛铛产品管理端接口服务",
  22. version="1.0.0",
  23. docs_url="/docs",
  24. redoc_url="/redoc",
  25. lifespan=lifespan_manager,
  26. )
  27. # CORS配置
  28. app.add_middleware(
  29. CORSMiddleware,
  30. allow_origins=["*"], # 生产环境应限制具体域名
  31. allow_credentials=True,
  32. allow_methods=["*"],
  33. allow_headers=["*"],
  34. )
  35. # API日志中间件(使用 ASGI 中间件以可靠捕获响应体)
  36. from app.middleware.auth import AuthValidationASGIMiddleware
  37. from app.middleware.logging import APILoggingASGIMiddleware
  38. # 日志中间件先执行,记录所有请求(包括未认证的)
  39. app.add_middleware(APILoggingASGIMiddleware)
  40. # 然后执行认证校验中间件,校验 token / 用户 / 卡密
  41. app.add_middleware(AuthValidationASGIMiddleware)
  42. # 异常处理
  43. from fastapi import HTTPException
  44. @app.exception_handler(HTTPException)
  45. async def http_exception_handler(request: Request, exc: HTTPException):
  46. """统一处理HTTPException,返回前端期望的格式"""
  47. return JSONResponse(
  48. status_code=exc.status_code,
  49. content={"code": exc.status_code, "msg": exc.detail}
  50. )
  51. @app.exception_handler(BusinessException)
  52. async def business_exception_handler(request: Request, exc: BusinessException):
  53. return JSONResponse(
  54. status_code=200,
  55. content={"code": exc.code, "msg": exc.msg}
  56. )
  57. @app.exception_handler(Exception)
  58. async def general_exception_handler(request: Request, exc: Exception):
  59. logger.error("未处理的异常", exc_info=True)
  60. return JSONResponse(
  61. status_code=500,
  62. content={"code": 500, "msg": "服务器内部错误"}
  63. )
  64. # 注册路由 - 只注册管理端接口
  65. from app.api.admin import router as admin_router
  66. from app.api.updater import router as updater_router
  67. app.include_router(admin_router, prefix="/admin", tags=["管理端接口"])
  68. app.include_router(updater_router, prefix="/admin", tags=["更新统计"])
  69. @app.get("/")
  70. async def root():
  71. """根路径"""
  72. return {"message": "游铛铛管理端API", "version": "1.0.0"}
  73. @app.get("/health")
  74. async def health():
  75. """健康检查"""
  76. return {"status": "ok"}
  77. if __name__ == "__main__":
  78. import uvicorn
  79. uvicorn.run(app, host="0.0.0.0", port=9999)