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

相关推荐
鹤卿12312 小时前
OC UI ——UIGestureRecognizer 手势识别
ui·ios·objective-c
阿正的梦工坊13 小时前
React:构建用户界面的JavaScript库
javascript·react.js·ui
Muyuan199814 小时前
31.Cursor 初体验:用 AI Agent 给 PaperPilot 做一次最小工程重构
人工智能·python·重构·django·fastapi·faiss
csdn小瓯15 小时前
FastAPI 依赖注入与状态管理实战:构建高可维护的异步后端
fastapi
ZC跨境爬虫15 小时前
跟着 MDN 学 HTML day_62:(HTML调试与常见错误修复指南)
java·前端·javascript·ui·html·媒体
赏金术士16 小时前
第二章:Compose入门—声明式UI编程
android·ui·kotlin·compose
dinl_vin16 小时前
FastAPI 系列(一)· 初体验——从 Spring Boot 工程师视角认识 FastAPI
后端·python·fastapi
多加点辣也没关系16 小时前
设计模式-命令模式
设计模式·命令模式
MilesShi16 小时前
UI 自动化的基本功:元素定位的原则、策略与实战经验
运维·ui·自动化
海市公约17 小时前
从 CRUD 到 AI 工程:基于 FastAPI + Dify 的 AI 面试模拟系统实践
prompt·fastapi·项目实战·dify·ai工作流·后端架构