main.py 7.4 KB

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