fastapi打不开swagger UI的问题

进行fastApi开发时,发现源码swagger静态资源访问不到,可能是网址出现了问题宕机了,我们可以有以下几种方式进行处理
源码的请求位置fastapi.openapi.docs.py get_swagger_ui_html
https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui-bundle.js
image
源码的调用位置fastapi.applications.py swagger_ui_html
image

1,在app实例化之前,进行重定向请求静态文件

from fastapi.openapi.docs import get_swagger_ui_html
from fastapi import FastAPI, applications
def swagger_monkey_patch(*args, **kwargs):
    return get_swagger_ui_html(
        *args, **kwargs,
        swagger_js_url='https://cdn.bootcdn.net/ajax/libs/swagger-ui/4.10.3/swagger-ui-bundle.js',
        swagger_css_url='https://cdn.bootcdn.net/ajax/libs/swagger-ui/4.10.3/swagger-ui.css'
    )
applications.get_swagger_ui_html = swagger_monkey_patch
## 正常实例化API操作
from fastapi import FastAPI
app = FastAPI()

2,直接在源码上,将这三个地址替换掉

替换成可以访问的远程地址
image
或者替换成本地的静态代理文件
image
然后再app加载时挂在静态路由

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")  # 加载静态文件

3,复制源代码中的方法,然后进行重新覆盖

image
sys.modules['fastapi.openapi.docs'].get_swagger_ui_html=my_get_swagger_ui_html
记住,引用了静态文件的,一定不要忘记了,挂载静态路由

posted @   darling331  阅读(2386)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示