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
from fastapi_cdn_host
import
monkey_patch_for_docs_ui
app =
FastAPI
()
monkey_patch_for_docs_ui(app)
尝试后无效,放弃了。
一个是把这两个URL对应的文件下载到本地的static目录中并挂载它,太麻烦,放弃了。
另外一个是在app启动前加一段寻址代码,也失败了
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 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入口
from fastapi importFastAPI
app = FastAPI(
title='xxx ',
description='xxx',
version='1.0.0'
)
from fastapi_offline importFastAPIOffline
app = FastAPIOffline(
title='xxx ',
description='xxx',
version='1.0.0'
)
本文分享自 python与大数据分析 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!