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"}

配置完再次访问

相关推荐
eqwaak05 分钟前
PyTorch张量操作全攻略:从入门到精通
开发语言·人工智能·pytorch·python
A懿轩A9 分钟前
Ghostty:告别 Mac 毛坯终端,打造 2026 最丝滑的 Ghostty AI 开发驾驶舱——Claude Code 团队也在用
python·macos·策略模式
Chasing Aurora10 分钟前
python 安装依赖和导入模块 详解
开发语言·python·虚拟环境·import·pyenv·requirements
念恒1230613 分钟前
Python(for循环)
python·学习
咱那飘逸的长发14 分钟前
Trae java项目配置全局maven和jdk
java·python·maven
码界筑梦坊24 分钟前
116-基于Flask的健身房会员锻炼数据可视化分析系统
python·信息可视化·数据分析·flask·毕业设计
wcy_101125 分钟前
QCoder智能生成Excel数据清洗与可视化代码
python·excel
财经资讯数据_灵砚智能1 小时前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年5月2日
人工智能·python·信息可视化·自然语言处理·ai编程
skiy1 小时前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
2601_956139421 小时前
集团品牌全案公司哪家专业
大数据·人工智能·python