""" 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 # 设置日志 logger = setup_logger() # 初始化密钥对 try: init_keys() except Exception as e: logger.error(f"密钥初始化失败: {e}") # 创建FastAPI应用 app = FastAPI( title="游铛铛API", description="游铛铛产品后端API", version="1.0.0", docs_url="/docs", redoc_url="/redoc", ) # CORS配置 app.add_middleware( CORSMiddleware, allow_origins=["*"], # 生产环境应限制具体域名 allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # API日志中间件 app.add_middleware(APILoggingMiddleware) # 异常处理 @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)