main.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from fastapi import FastAPI, Depends
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from fastapi.openapi.utils import get_openapi
  4. from fastapi.security import HTTPBearer
  5. from app.api import router
  6. from app.core.auth import verify_token
  7. from app.core.config import settings
  8. app = FastAPI(title=settings.app_name)
  9. # -----------------------
  10. # CORS(可选)
  11. # -----------------------
  12. app.add_middleware(
  13. CORSMiddleware,
  14. allow_origins=["*"],
  15. allow_methods=["*"],
  16. allow_headers=["*"],
  17. )
  18. # -----------------------
  19. # 路由注册
  20. # -----------------------
  21. # 公共路由,不鉴权
  22. app.include_router(
  23. router.public_router,
  24. prefix="/api"
  25. )
  26. # 需要鉴权的路由
  27. app.include_router(
  28. router.protected_router,
  29. prefix="/api",
  30. #dependencies=[Depends(verify_token)]
  31. )
  32. # -----------------------
  33. # Swagger 支持 Bearer Token
  34. # -----------------------
  35. def custom_openapi():
  36. if app.openapi_schema:
  37. return app.openapi_schema
  38. openapi_schema = get_openapi(
  39. title=app.title,
  40. version="1.0.0",
  41. description="API documentation",
  42. routes=app.routes,
  43. )
  44. # 添加全局 Bearer
  45. openapi_schema["components"]["securitySchemes"] = {
  46. "BearerAuth": {
  47. "type": "http",
  48. "scheme": "bearer",
  49. "bearerFormat": "JWT"
  50. }
  51. }
  52. for path in openapi_schema["paths"].values():
  53. for method in path.values():
  54. method["security"] = [{"BearerAuth": []}]
  55. app.openapi_schema = openapi_schema
  56. return app.openapi_schema
  57. app.openapi = custom_openapi