【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。

相关推荐
Python私教6 小时前
FastAPI 与 JWT 身份验证:保护你的 API
网络·fastapi
白嫖不白嫖1 天前
Django、Flask、FastAPI与Jupyter对比
django·flask·fastapi
一刀到底2111 天前
Python 高级应用10:在python 大型项目中 FastAPI 和 Django 的相互配合
python·django·fastapi
中国软件测试质量协会1 天前
UI自动化测试:现状,效果和最佳实践
ui·自动化·ui自动化·webui·界面自动化
派阿喵搞电子2 天前
在UI界面内修改了对象名,在#include “ui_mainwindow.h“没更新
c++·qt·ubuntu·ui
pop_xiaoli2 天前
OC—UI学习-2
学习·ui·ios
fengbingchun2 天前
线性规划饮食问题求解:FastAPI作为服务端+libhv作为客户端实现
fastapi·libhv·pyomo
zhangsan09332 天前
web框架(Django 与 FastAPI)
django·fastapi
jingyucsdn2 天前
网页端 VUE+C#/FastAPI获取客户端IP和hostname
网络协议·tcp/ip·fastapi
界面开发小八哥2 天前
界面开发框架DevExpress XAF实践:集成.NET Aspire后如何实现数据库依赖?
ui·.net·界面控件·devexpress·ui开发·xaf