| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- """
- FastAPI应用入口 - 管理端接口服务
- """
- from fastapi import FastAPI, Request
- from fastapi.middleware.cors import CORSMiddleware
- from fastapi.responses import JSONResponse
- from app.api.admin import router as admin_router
- from app.core.logger import setup_logger
- from app.utils.exceptions import BusinessException
- from app.background_tasks import lifespan_manager
- from app.core.config_cache import config_cache
- # 设置日志
- logger = setup_logger()
- # 启动时加载配置
- logger.info("启动时加载系统配置...")
- config_cache.load_configs()
- logger.info(f"系统配置加载完成,共 {len(config_cache.get_all())} 项配置")
- # 创建FastAPI应用
- app = FastAPI(
- title="游铛铛管理端API",
- description="游铛铛产品管理端接口服务",
- version="1.0.0",
- docs_url="/docs",
- redoc_url="/redoc",
- lifespan=lifespan_manager,
- )
- # CORS配置
- app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"], # 生产环境应限制具体域名
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
- )
- # API日志中间件(使用 ASGI 中间件以可靠捕获响应体)
- from app.middleware.auth import AuthValidationASGIMiddleware
- from app.middleware.logging import APILoggingASGIMiddleware
- # 日志中间件先执行,记录所有请求(包括未认证的)
- app.add_middleware(APILoggingASGIMiddleware)
- # 然后执行认证校验中间件,校验 token / 用户 / 卡密
- app.add_middleware(AuthValidationASGIMiddleware)
- # 异常处理
- from fastapi import HTTPException
- @app.exception_handler(HTTPException)
- async def http_exception_handler(request: Request, exc: HTTPException):
- """统一处理HTTPException,返回前端期望的格式"""
- return JSONResponse(
- status_code=exc.status_code,
- content={"code": exc.status_code, "msg": exc.detail}
- )
- @app.exception_handler(BusinessException)
- async def business_exception_handler(request: Request, exc: BusinessException):
- return JSONResponse(
- status_code=200,
- content={"code": exc.code, "msg": exc.msg}
- )
- @app.exception_handler(Exception)
- async def general_exception_handler(request: Request, exc: Exception):
- logger.error("未处理的异常", exc_info=True)
- return JSONResponse(
- status_code=500,
- content={"code": 500, "msg": "服务器内部错误"}
- )
- # 注册路由 - 只注册管理端接口
- from app.api.admin import router as admin_router
- from app.api.updater import router as updater_router
- app.include_router(admin_router, prefix="/admin", tags=["管理端接口"])
- app.include_router(updater_router, prefix="/admin", tags=["更新统计"])
- @app.get("/")
- async def root():
- """根路径"""
- return {"message": "游铛铛管理端API", "version": "1.0.0"}
- @app.get("/health")
- async def health():
- """健康检查"""
- return {"status": "ok"}
- if __name__ == "__main__":
- import uvicorn
- uvicorn.run(app, host="0.0.0.0", port=9999)
|