build_app.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from fastapi import FastAPI, Request
  2. from fastapi.openapi.docs import (
  3. get_redoc_html,
  4. get_swagger_ui_html,
  5. get_swagger_ui_oauth2_redirect_html,
  6. )
  7. from fastapi.responses import JSONResponse
  8. from fastapi.staticfiles import StaticFiles
  9. import setting
  10. from exception import ApiException
  11. from services.limiter import register_limiter
  12. from services.routers import service_router
  13. def register_swagger_ui_html(app):
  14. app.mount("/static", StaticFiles(directory="static"), name="static")
  15. @app.get("/docs", include_in_schema=False)
  16. async def custom_swagger_ui_html():
  17. return get_swagger_ui_html(
  18. openapi_url=app.openapi_url,
  19. title=app.title + " - Swagger UI",
  20. oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
  21. swagger_js_url="/static/swagger-ui-bundle.js",
  22. swagger_css_url="/static/swagger-ui.css",
  23. )
  24. @app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
  25. async def swagger_ui_redirect():
  26. return get_swagger_ui_oauth2_redirect_html()
  27. @app.get("/redoc", include_in_schema=False)
  28. async def redoc_html():
  29. return get_redoc_html(
  30. openapi_url=app.openapi_url,
  31. title=app.title + " - ReDoc",
  32. redoc_js_url="/static/redoc.standalone.js",
  33. )
  34. def init_app():
  35. if setting.PLATFORM_ENVIRONMENT != "prod":
  36. app = FastAPI(title="Captcha", docs_url=None, redoc_url=None)
  37. register_swagger_ui_html(app)
  38. else:
  39. # 生产环境关闭文档说明
  40. app = FastAPI(title="Captcha", docs_url=None, redoc_url=None)
  41. app.include_router(service_router, prefix="/v1")
  42. @app.exception_handler(ApiException)
  43. async def api_exception(request: Request, exc: ApiException):
  44. return JSONResponse(status_code=200, content=dict(code=exc.code, errMsg=exc.errMsg, r=exc.r))
  45. @app.exception_handler(Exception)
  46. async def unknown_exception(request: Request, exc: Exception):
  47. return JSONResponse(status_code=500, content=dict(code=1, errMsg="服务器内部错误,暂无法提供服务", r={}))
  48. return app
  49. def create_app():
  50. app = init_app()
  51. register_limiter(app)
  52. return app