暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

关于FastAPI文档无法显示的问题

追梦IT人 2024-03-12
1256

Python调试和部署总会碰到各种各样的问题,Python的版本问题,各种包的版本问题,Python的调试和部署快成了一门玄学,这次遭遇到的是FastAPI文档界面无法显示的问题,中间也测试过几种方案。

FastAPI部署后,各页面均正常响应,除了文档页,经查证是FastAPI接口文档中默认使用的是https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css和https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js来渲染页面,而这两个URL是外网的CDN,在国内响应超慢,导致请求超时了。

对于这个问题解决方案有好多种,一个是安装pip install fastapi_cdn_host

  1. from fastapi_cdn_host import monkey_patch_for_docs_ui

  2. app = FastAPI()

  3. monkey_patch_for_docs_ui(app)

尝试后无效,放弃了。

一个是把这两个URL对应的文件下载到本地的static目录中并挂载它,太麻烦,放弃了。

另外一个是在app启动前加一段寻址代码,也失败了

  1. def swagger_monkey_patch(*args, **kwargs):

  2. """

  3. Wrap the function which is generating the HTML for the docs endpoint and

  4. overwrite the default values for the swagger js and css.

  5. """

  6. # 国内优秀的资源库 https://www.liangwei.cc/website_tech/jsdelivr_zha_le_guo_nei_ti_dai_fang_an.html, 这里用的是七牛云的

  7. return get_swagger_ui_html(

  8. *args, **kwargs,

  9. swagger_js_url="https://cdn.staticfile.org/swagger-ui/5.2.0/swagger-ui-bundle.min.js",

  10. swagger_css_url="https://cdn.staticfile.org/swagger-ui/5.2.0/swagger-ui.min.css")



  11. # Actual monkey patch

  12. applications.get_swagger_ui_html = swagger_monkey_patch

最后找到一种更佳的方案,选择用FastAPI离线文档方式。具体参见https://pypi.org/project/fastapi-offline/

FastAPI is awesome, but the documentation pages (Swagger or Redoc) all depend on external CDNs, which is problematic if you want to run on disconnected networks.

This package includes the required files from the CDN and serves them locally. It also provides a super-simple way to get a FastAPI instance configured to use those files.

Under the hood, this simply automates the process described in the official documentation here.

首先pip install fastapi-offline

其次是查找原来的fastapi入口

  1. from fastapi importFastAPI

  2. app = FastAPI(

  3. title='xxx ',

  4. description='xxx',

  5. version='1.0.0'

  6. )

再次是替换原来的api入口

  1. from fastapi_offline importFastAPIOffline

  2. app = FastAPIOffline(

  3. title='xxx ',

  4. description='xxx',

  5. version='1.0.0'

  6. )

最后问题得以解决!

最后欢迎关注公众号:python与大数据分析


文章转载自追梦IT人,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论