fastapi 无法正常加载可视化API文档界面的/docs网页本地显示

fastapi /docs网页本地显示

/docs因为网络原因,访问空白,自定义swagger_ui,
让swagger-ui.css和swagger-ui-bundle.js等静态资源从本地进行加载,可解决问题,并且可无网络访问

1 查看fastapi源文件

def get_swagger_ui_html(
    *,
    openapi_url: str,
    title: str,
    swagger_js_url: str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js",
    swagger_css_url: str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css",
    swagger_favicon_url: str = "https://fastapi.tiangolo.com/img",
    oauth2_redirect_url: str | None = None,
    init_oauth: Dict[str, Any] | None = None,
    swagger_ui_parameters: Dict[str, Any] | None = None
) -> HTMLResponse

通过函数传递的参数值可以看出,默认的swagger_js_url和swagger_css_url使用了网络地址,所以可以从这里入手进行改造。

2 下载swagger_js_url和swagger_css_url对应的资源文件,然后将它们放到static文件夹之下。

3 挂载相关静态资源文件,设置读取路径并自定义访问docs路由

import pathlib
from fastapi import FastAPI
from fastapi.openapi.docs import (get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html,)
from fastapi.staticfiles import StaticFiles

# 重置docs_url 
app = FastAPI(docs_url=None)  

# 挂载相关静态资源文件     
app.mount("/static", StaticFiles(directory=f"{pathlib.Path.cwd()}/static"), name="static")

# 修改静态资源文件获取地址
@app.get('/docs', include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=app.title + " - Swagger UI",
        oauth2_redirect_url= app.swagger_ui_oauth2_redirect_url,
        swagger_js_url="/static/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui.css",
        swagger_favicon_url="https://fastapi.tiangolo.com/img/favicon.png"
    )

@app.get('/root')
def root():
    return "hello world"

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app='fast:app', reload=True)

4 步骤4 启动服务,然后查看浏览器请求信息(打开浏览器,按下F12键),此时会发现swagger_js_url和swagger_css_url已经默认从本地加载了

在这里插入图片描述

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值