FastApi接口文档访问超时加载不出来解决方案来了

10 阅读1分钟

问题

FastApi 默认接口文档地址 加载不出来空白页面。

原因

FastApi 默认使用了swagger-ui.css swagger-ui-bundle.js 来渲染文档页面,这两个都是国外cdn所以响应慢,会出现超时情况。

image.png

解决方法

把这两个文件下载到本地swagger-ui.css swagger-ui-bundle.js ,直接使用本地静态文件。

首先下载两个静态文件,在本项目目录下手动创建static文件夹

css和js文件下载到本地 swagger-ui.css 下载地址 swagger-ui-bundle.js 下载地址

复制swagger-ui.css swagger-ui-bundle.js 代码,全选【CTRL+A】粘贴到本地static 文件下,同时创建swagger-ui.css swagger-ui-bundle.js 两个文件。 如下图:

swagger-ui-bundle.js image.png‘’

swagger-ui.css

image.png

image.png

然后修改FastApi 文档资源访问本地资源文件。

FastApi 代码配置如下


from fastapi import FastAPI,Path
from pydantic import BaseModel
from fastapi.openapi.docs import get_swagger_ui_html
from starlette.staticfiles import StaticFiles

app = FastAPI(docs_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=app.openapi_url,
        title="Swagger UI(定制)",
        swagger_js_url="/static/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui.css";
    )

@app.get("/")
async def root():
    return {"message": "Hello World Python FastApi"}

配置完再次访问

image.png