前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于FastAPI文档无法显示的问题

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

作者头像
python与大数据分析
发布2024-03-13 15:52:06
1910
发布2024-03-13 15:52:06
举报

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

代码语言:javascript
复制
from fastapi_cdn_host 
import
 monkey_patch_for_docs_ui

app = 
FastAPI
()

monkey_patch_for_docs_ui(app)

尝试后无效,放弃了。

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

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

代码语言:text
复制

def swagger_monkey_patch(*args, **kwargs):
 
"""
 
Wrap the function which is generating the HTML for the /docs endpoint and
 
    overwrite the default values for the swagger js and css.
 
"""
 
# 国内优秀的资源库 https://www.liangwei.cc/website_tech/jsdelivr_zha_le_guo_nei_ti_dai_fang_an.html, 这里用的是七牛云的
 
return get_swagger_ui_html(
 
*args, **kwargs,
 
        swagger_js_url="https://cdn.staticfile.org/swagger-ui/5.2.0/swagger-ui-bundle.min.js",
 
        swagger_css_url="https://cdn.staticfile.org/swagger-ui/5.2.0/swagger-ui.min.css")
 

 

 
# Actual monkey patch
 
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入口

代码语言:text
复制
from fastapi importFastAPI
 
app = FastAPI(
 
    title='xxx ',
 
    description='xxx',
 
    version='1.0.0'
 
)

再次是替换原来的api入口

代码语言:text
复制
from fastapi_offline importFastAPIOffline
 
app = FastAPIOffline(
 
    title='xxx ',
 
    description='xxx',
 
    version='1.0.0'
 
)
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2024-03-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 python与大数据分析 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 最后找到一种更佳的方案,选择用FastAPI离线文档方式。具体参见https://pypi.org/project/fastapi-offline/
  • 再次是替换原来的api入口
相关产品与服务
内容分发网络 CDN
内容分发网络(Content Delivery Network,CDN)通过将站点内容发布至遍布全球的海量加速节点,使其用户可就近获取所需内容,避免因网络拥堵、跨运营商、跨地域、跨境等因素带来的网络不稳定、访问延迟高等问题,有效提升下载速度、降低响应时间,提供流畅的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档