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

问题

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

原因

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

解决方法

把这两个文件下载到本地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 ''

swagger-ui.css

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

FastApi 代码配置如下

python 复制代码
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"}

配置完再次访问

相关推荐
AI探索者15 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者15 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh17 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅17 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽18 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python