main.py 7.0 KB

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