main.py 6.6 KB

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