本地Swagger资源
前言
FastAPI 的 Swagger UI 默认会从第三方 CDN 下载 JS 和 CSS 资源,在网络环境受限(内网/离线)时可以改为从本地加载静态资源。
步骤
Swagger 页面 HTML 由 site-packages/fastapi/openapi/docs.py 中的 get_swagger_ui_html 方法渲染,默认引用的 swagger_js_url、swagger_css_url、swagger_favicon_url 都是 CDN 地址。先把这三个文件下载到项目的 static/ 目录,再重写 /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
app = FastAPI(
title="Hello FastAPI",
description="Quickstart of FastAPI",
version="0.1.0",
docs_url=None,
)
# 挂载静态资源
app.mount("/static", StaticFiles(directory=f"{pathlib.Path.cwd()}/static"), name="static")
@app.get("/docs", include_in_schema=False)
async def local_swagger_ui():
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="/static/favicon.png",
)
备注
下载地址可以在 fastapi/openapi/docs.py 源码中查到;Swagger UI 版本会随 FastAPI 升级,建议锁定下载版本与当前 FastAPI 内置版本一致。