build_app.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import os
  2. from fastapi import FastAPI, Request
  3. from fastapi.openapi.docs import (
  4. get_redoc_html,
  5. get_swagger_ui_html,
  6. get_swagger_ui_oauth2_redirect_html,
  7. )
  8. from fastapi.responses import JSONResponse
  9. from fastapi.staticfiles import StaticFiles
  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. env = os.getenv("FASTAPI_ENV")
  36. if env != "prod":
  37. app = FastAPI(title="Captcha", docs_url=None, redoc_url=None)
  38. register_swagger_ui_html(app)
  39. else:
  40. # 生产环境关闭文档说明
  41. app = FastAPI(title="Captcha", docs_url=None, redoc_url=None)
  42. app.include_router(service_router, prefix="/v1")
  43. @app.exception_handler(ApiException)
  44. async def api_exception(request: Request, exc: ApiException):
  45. return JSONResponse(status_code=200, content=dict(code=exc.code, errMsg=exc.errMsg, r=exc.r))
  46. @app.exception_handler(Exception)
  47. async def unknown_exception(request: Request, exc: Exception):
  48. return JSONResponse(status_code=500, content=dict(code=1, errMsg="服务器内部错误,暂无法提供服务", r={}))
  49. return app
  50. def create_app():
  51. app = init_app()
  52. register_limiter(app)
  53. return app