FastAPI 接口文档访问速度的解决方案
引言
在使用 FastAPI 开发 RESTful API 时,其自动生成的 Swagger UI 和 ReDoc 文档为开发者和用户提供了极大的便利。然而,在实际应用中,我们可能会遇到接口文档加载速度慢的问题,这不仅影响开发效率,还可能给用户体验带来负面影响。本文将探讨导致 FastAPI 接口文档访问速度慢的常见原因,并提供相应的解决方案。
1. 问题分析
1.1 文档生成机制
FastAPI 的 /docs
和 /redoc
页面是基于 OpenAPI 规范自动生成的,这意味着每次请求这些页面时,FastAPI 都会重新生成对应的 JSON 文档。如果 API 规模较大或结构复杂,这个生成过程可能会消耗较多时间,导致页面加载缓慢。
1.2 静态资源加载
Swagger UI 和 ReDoc 页面依赖于一些静态资源(如 CSS、JS 文件)来渲染界面。如果这些静态资源的加载速度慢,同样会影响整体的页面加载速度。
1.3 网络因素
网络延迟、带宽限制等外部因素也会对文档页面的加载速度产生影响。特别是在网络环境较差的情况下,文档页面的响应时间会显著增加。
2. 解决方案
使用本地静态资源
默认情况下,Swagger UI 和 ReDoc 会从远程服务器加载静态资源。为了加快加载速度,我们可以使用本地静态资源。具体步骤如下:
- 下载静态资源:
https://cloud.189.cn/web/share?code=UrueeuRBfyYz(访问码:6ev9)
将 swagger-ui-bundle.js、swagger-ui.css 等静态文件下载到项目中的static/swagger-ui
目录。 - 配置静态资源路径:在 FastAPI 应用中配置静态资源路径。
from fastapi.staticfiles import StaticFiles
app.mount("/static", StaticFiles(directory="static"), name="static")
- 替换默认静态资源 URL:在
main.py
中替换默认的静态资源 URL。
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html
app = FastAPI(
title="Fastapi",
version="0.1.0",
description="这是接口文档的描述",
docs_url=None,
redoc_url=None
)
# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url="/openapi.json",
title= app.title + " - Swagger UI",
swagger_js_url="/static/swagger-ui/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui/swagger-ui.css",
swagger_favicon_url="/static/swagger-ui/favicon.png",
# 自定义 Swagger UI 配置项
swagger_ui_parameters={
# 控制模型定义的初始展开深度。设置为 -1 可以完全隐藏模型部分
"defaultModelsExpandDepth": -1,
# 控制文档中操作的初始展开状态
# "none":所有操作都折叠
# "list":列出所有操作,但细节折叠
# "full":所有操作及其细节都展开
"docExpansion": "list",
"syntaxHighlight": {"theme": "monokai"},
# 是否启用顶部搜索框来过滤操作
"filter": True,
# 是否保持授权状态,以便在不同操作间共享授权信息
"persistAuthorization": True,
# 否显示请求的持续时间
"displayRequestDuration": True,
}
)
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
return get_redoc_html(
openapi_url="/openapi.json",
title= app.title + " - ReDoc",
redoc_js_url="/static/swagger-ui/redoc.standalone.js",
redoc_favicon_url="/static/swagger-ui/favicon.png",
with_google_fonts=False,
)
启动fastapi项目,然后请求http://ip+端口/docs,可以看到,请求的是本地的css、js文件了