【FastAPI】离线使用Swagger UI 或 国内网络如何快速加载Swagger UI

在FastAPI中,默认情况下,当应用启动时,Swagger UI 会通过在线加载 Swagger UI 的静态资源。这意味着如果应用运行在没有互联网连接的环境中,默认的 Swagger 文档页面将无法加载。

为了在离线环境中使用 Swagger UI,你需要手动加载 Swagger UI 的静态文件并将其与 FastAPI 集成。以下是具体步骤:

1. 下载 Swagger UI 静态资源

  • 首先,你需要下载 Swagger UI 的静态文件,或者你可以直接从 官方文档页面 下载。
  • 下载后,你可以将静态文件放置在项目中的某个文件夹中,例如:./static/swagger-ui/
  • 备用方案 :在浏览器中加载你服务的swagger界面,在debug界面找到swagger资源请求的url,下载文件。如下图所示:

2. 配置 FastAPI 以使用本地 Swagger UI 资源

你可以通过 FastAPI 提供的 swagger_ui_init_oauth 参数,指定加载本地的 Swagger UI 文件。以下是一个实现示例:

python 复制代码
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.staticfiles import StaticFiles

app = FastAPI(docs_url=None)

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

# 自定义 Swagger 文档路由,指向本地的 Swagger UI 文件
@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",
        swagger_js_url="/static/swagger-ui/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui/swagger-ui.css"
    )

@app.get("/")
async def read_root():
    return {"Hello": "World"}

# 自定义 OpenAPI 文档路由
@app.get("/openapi.json", include_in_schema=False)
async def get_openapi():
    return app.openapi()

3. 将本地静态资源与 FastAPI 配置集成

在这个示例中,/static 路径被用来提供本地 Swagger UI 的静态文件。get_swagger_ui_html() 函数用于生成 Swagger 文档的页面,并且使用本地的 JavaScript 和 CSS 文件。

目录结构示例

复制代码
.
├── main.py  # FastAPI 代码文件
└── static
    └── swagger-ui
        ├── swagger-ui-bundle.js
        ├── swagger-ui.css
        └── ... (其他 Swagger UI 的静态文件)

4. 运行应用

运行 FastAPI 应用,访问 http://localhost:8000/docs,就可以在离线状态下正常访问 Swagger UI 文档页面了。

通过这种方式,你可以在无网络连接的情况下依然加载和使用 Swagger UI。

相关推荐
烟锁池塘柳014 小时前
【技术栈-前端】告别“转圈圈”:详解前端性能优化之“乐观 UI” (Optimistic UI)
前端·ui
中年程序员一枚19 小时前
python开发接口uvicorn方法启动FastAPI,postman调用接口
python·postman·fastapi
yuegu77720 小时前
DevUI Modal 模态弹窗组件使用详解
ui·前端框架
少年张二狗21 小时前
Vue + Element-UI 图片上传实现拖拽排序功能
前端·vue.js·ui
sailing-data1 天前
【UI Qt】入门笔记
开发语言·qt·ui
L、2181 天前
Flutter + OpenHarmony 分布式能力融合:实现跨设备 UI 共享与协同控制(终极篇)
javascript·分布式·flutter·ui·智能手机·harmonyos
鸿蒙开发工程师—阿辉1 天前
HarmonyOS 5 极致动效实验室:给 UI 注入“物理动效”
ui·华为·harmonyos
周杰伦_Jay1 天前
【FastAPI】核心特性、目录结构与生产级实践
架构·开源·fastapi
道19932 天前
QT 工程中快速实现中英文切换(含动态切换)
命令模式