main.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. from contextlib import asynccontextmanager
  2. from fastapi import FastAPI, Depends, Request
  3. from fastapi.responses import JSONResponse
  4. from fastapi.middleware.cors import CORSMiddleware
  5. from fastapi.openapi.utils import get_openapi
  6. from fastapi.exceptions import RequestValidationError
  7. from starlette.exceptions import HTTPException as StarletteHTTPException
  8. import time
  9. from app.api import router
  10. from app.core.database import AsyncSessionLocal
  11. from app.core.auth import RoleLevel, require_min_role
  12. from app.core.config import settings
  13. from app.core.payment import init_stripe
  14. from app.core.biz_exception import BizException
  15. from app.core.logger import logger, access_logger
  16. @asynccontextmanager
  17. async def lifespan(app: FastAPI):
  18. init_stripe()
  19. logger.info("🟢 Stripe config done")
  20. yield
  21. app = FastAPI(title=settings.app_name, lifespan=lifespan)
  22. # -----------------------
  23. # Access Log & Performance Middleware
  24. # -----------------------
  25. @app.middleware("http")
  26. async def access_log_middleware(request: Request, call_next):
  27. start_time = time.perf_counter()
  28. client_ip = request.client.host if request.client else "unknown"
  29. method = request.method
  30. path = request.url.path
  31. query = request.url.query
  32. full_path = f"{path}?{query}" if query else path
  33. try:
  34. response = await call_next(request)
  35. process_time_ms = (time.perf_counter() - start_time) * 1000.0
  36. status_code = response.status_code
  37. if process_time_ms > 1000:
  38. logger.warning(
  39. f"⚠️ [SLOW REQUEST] {method} {full_path} | ip={client_ip} | status={status_code} | duration={process_time_ms:.2f}ms"
  40. )
  41. access_logger.info(
  42. f"{method} {full_path} | ip={client_ip} | status={status_code} | duration={process_time_ms:.2f}ms"
  43. )
  44. return response
  45. except Exception as exc:
  46. process_time_ms = (time.perf_counter() - start_time) * 1000.0
  47. logger.error(
  48. f"❌ [REQUEST ERROR] {method} {full_path} | ip={client_ip} | duration={process_time_ms:.2f}ms | error: {exc}",
  49. exc_info=True,
  50. )
  51. raise exc
  52. # -----------------------
  53. # Exception Handlers
  54. # -----------------------
  55. @app.exception_handler(BizException)
  56. async def biz_exception_handler(request: Request, exc: BizException):
  57. logger.warning(
  58. f"⚠️ [BIZ ERROR] {request.method} {request.url.path} | code={exc.code} | msg={exc.message}"
  59. )
  60. return JSONResponse(
  61. status_code=exc.http_status,
  62. content={
  63. "code": exc.code,
  64. "message": exc.message,
  65. "data": exc.extra,
  66. },
  67. )
  68. @app.exception_handler(Exception)
  69. async def unhandled_exception_handler(request: Request, exc: Exception):
  70. client_ip = request.client.host if request.client else "unknown"
  71. logger.error(
  72. f"💥 [500 UNHANDLED EXCEPTION] {request.method} {request.url.path} | ip={client_ip}",
  73. exc_info=exc,
  74. )
  75. return JSONResponse(
  76. status_code=500,
  77. content={
  78. "code": 50000,
  79. "message": "Internal Server Error",
  80. "data": None,
  81. },
  82. )
  83. @app.exception_handler(RequestValidationError)
  84. async def validation_exception_handler(request: Request, exc: RequestValidationError):
  85. """
  86. 接管 FastAPI 默认的 422 数据校验错误
  87. """
  88. # 1. 获取所有的错误详情
  89. errors = exc.errors()
  90. # 2. 提取第一个错误作为主要提示信息(通常用户只关心第一个报错)
  91. if errors:
  92. first_error = errors[0]
  93. # 处理路径:去掉 'body', 'query' 等前缀,只保留字段名,用点连接
  94. # 例如: ['body', 'user', 'age'] -> 'user.age'
  95. # 如果路径只有 ['body'] (比如传了空JSON),则通过 [1:] 过滤可能为空,要做个保护
  96. raw_path = first_error.get("loc", [])
  97. path_parts = [str(p) for p in raw_path if p not in ('body', 'query', 'path')]
  98. field_path = ".".join(path_parts) if path_parts else "request_body"
  99. err_msg = first_error.get("msg")
  100. # 优化提示文案
  101. message = f"Invalid parameter [{field_path}]: {err_msg}"
  102. else:
  103. message = "Invalid request parameters"
  104. # 3. 返回标准格式
  105. return JSONResponse(
  106. status_code=422,
  107. content={
  108. "code": 42200, # 或者是你们约定的参数错误码
  109. "message": message, # 转换后的人类可读提示
  110. "data": errors # 保留原始错误详情,方便前端开发排查
  111. },
  112. )
  113. @app.exception_handler(StarletteHTTPException)
  114. async def http_exception_handler(request: Request, exc: StarletteHTTPException):
  115. """
  116. 接管所有 HTTP 错误,包括 404 Not Found 和 405 Method Not Allowed
  117. """
  118. return JSONResponse(
  119. status_code=exc.status_code,
  120. content={
  121. # 这里你可以根据 status_code 生成你的业务 code,比如 404 -> 40400
  122. "code": exc.status_code*100,
  123. "message": exc.detail, # 这里通常是 "Not Found"
  124. "data": None,
  125. },
  126. )
  127. # -----------------------
  128. # CORS
  129. # -----------------------
  130. app.add_middleware(
  131. CORSMiddleware,
  132. allow_origins=["*"],
  133. allow_methods=["*"],
  134. allow_headers=["*"],
  135. )
  136. # -----------------------
  137. # Routers
  138. # -----------------------
  139. app.include_router(
  140. router.public_router,
  141. prefix="/api"
  142. )
  143. app.include_router(
  144. router.protected_router,
  145. prefix="/api",
  146. dependencies=[Depends(require_min_role(RoleLevel.user))]
  147. )
  148. app.include_router(
  149. router.admin_required_router,
  150. prefix="/api",
  151. dependencies=[Depends(require_min_role(RoleLevel.admin))]
  152. )
  153. # -----------------------
  154. # Swagger Bearer Token
  155. # -----------------------
  156. def custom_openapi():
  157. if app.openapi_schema:
  158. return app.openapi_schema
  159. openapi_schema = get_openapi(
  160. title=app.title,
  161. version="1.0.0",
  162. description="API documentation",
  163. routes=app.routes,
  164. )
  165. openapi_schema.setdefault("components", {})
  166. openapi_schema["components"]["securitySchemes"] = {
  167. "BearerAuth": {
  168. "type": "http",
  169. "scheme": "bearer",
  170. "bearerFormat": "JWT",
  171. }
  172. }
  173. for path in openapi_schema["paths"].values():
  174. for method in path.values():
  175. method.setdefault("security", [])
  176. method["security"].append({"BearerAuth": []})
  177. app.openapi_schema = openapi_schema
  178. return app.openapi_schema
  179. app.openapi = custom_openapi