main.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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.client import router as client_router
  8. from app.api.admin import router as admin_router
  9. from app.core.logger import setup_logger
  10. from app.core.init_keys import init_keys
  11. from app.middleware.logging import APILoggingMiddleware
  12. from app.utils.exceptions import BusinessException
  13. # 设置日志
  14. logger = setup_logger()
  15. # 初始化密钥对
  16. try:
  17. init_keys()
  18. except Exception as e:
  19. logger.error(f"密钥初始化失败: {e}")
  20. # 创建FastAPI应用
  21. app = FastAPI(
  22. title="游铛铛API",
  23. description="游铛铛产品后端API",
  24. version="1.0.0",
  25. docs_url="/docs",
  26. redoc_url="/redoc",
  27. )
  28. # CORS配置
  29. app.add_middleware(
  30. CORSMiddleware,
  31. allow_origins=["*"], # 生产环境应限制具体域名
  32. allow_credentials=True,
  33. allow_methods=["*"],
  34. allow_headers=["*"],
  35. )
  36. # API日志中间件
  37. app.add_middleware(APILoggingMiddleware)
  38. # 异常处理
  39. @app.exception_handler(BusinessException)
  40. async def business_exception_handler(request: Request, exc: BusinessException):
  41. return JSONResponse(
  42. status_code=200,
  43. content={"code": exc.code, "msg": exc.msg}
  44. )
  45. @app.exception_handler(Exception)
  46. async def general_exception_handler(request: Request, exc: Exception):
  47. logger.error(f"未处理的异常: {exc}", exc_info=True)
  48. return JSONResponse(
  49. status_code=500,
  50. content={"code": 500, "msg": "服务器内部错误"}
  51. )
  52. # 注册路由
  53. app.include_router(client_router, prefix="/api", tags=["客户端接口"])
  54. app.include_router(admin_router, prefix="/admin", tags=["管理端接口"])
  55. @app.get("/")
  56. async def root():
  57. """根路径"""
  58. return {"message": "游铛铛API", "version": "1.0.0"}
  59. @app.get("/health")
  60. async def health():
  61. """健康检查"""
  62. return {"status": "ok"}
  63. if __name__ == "__main__":
  64. import uvicorn
  65. uvicorn.run(app, host="0.0.0.0", port=8000)