| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133 |
- """
- FastAPI应用入口
- """
- from fastapi import FastAPI, Request
- from fastapi.middleware.cors import CORSMiddleware
- from fastapi.responses import JSONResponse
- from app.api.client import router as client_router
- from app.api.admin import router as admin_router
- from app.core.logger import setup_logger
- from app.core.init_keys import init_keys
- from app.middleware.logging import APILoggingMiddleware
- from app.utils.exceptions import BusinessException
- from app.background_tasks import lifespan_manager
- # 设置日志
- logger = setup_logger()
- # 初始化密钥对
- try:
- init_keys()
- logger.info("基础密钥初始化完成")
- except Exception as e:
- logger.exception("基础密钥初始化失败")
- # 初始化密钥轮换系统
- try:
- from app.services.key_rotation_service import KeyRotationService
- from app.database import get_db
- db = next(get_db())
- if KeyRotationService.initialize_keys(db):
- logger.info("密钥轮换系统初始化成功")
- else:
- logger.error("密钥轮换系统初始化失败")
- db.close()
- except Exception as e:
- logger.exception("密钥轮换系统初始化异常")
- # 初始化Session清理
- try:
- from app.services.session_service import SessionService
- from app.database import get_db
- db = next(get_db())
- cleaned_count = SessionService.cleanup_expired_sessions(db)
- if cleaned_count > 0:
- logger.info(f"清理了 {cleaned_count} 个过期会话")
- else:
- logger.info("没有需要清理的过期会话")
- db.close()
- except Exception as e:
- logger.exception("Session清理初始化异常")
- # 初始化心跳监控
- try:
- from app.services.heartbeat_monitor import HeartbeatMonitor
- cleaned_cache = HeartbeatMonitor.cleanup_cache()
- if cleaned_cache > 0:
- logger.info(f"清理了 {cleaned_cache} 个过期的缓存条目")
- else:
- logger.info("心跳缓存状态正常")
- except Exception as e:
- logger.exception("心跳监控初始化异常")
- # 创建FastAPI应用
- app = FastAPI(
- title="游铛铛API",
- description="游铛铛产品后端API",
- 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
- # 认证校验中间件先执行,校验 token / 用户 / 卡密
- app.add_middleware(AuthValidationASGIMiddleware)
- # 然后记录 API 日志(依赖认证信息)
- app.add_middleware(APILoggingASGIMiddleware)
- # 异常处理
- 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(f"未处理的异常: {exc}", exc_info=True)
- return JSONResponse(
- status_code=500,
- content={"code": 500, "msg": "服务器内部错误"}
- )
- # 注册路由
- app.include_router(client_router, prefix="/api", tags=["客户端接口"])
- app.include_router(admin_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=8000)
|