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

配置完再次访问

相关推荐
二十雨辰4 小时前
[爬虫]-Urllib
爬虫·python
玉鸯5 小时前
Agent Hook:在概率推理之上,为 Agent 叠加确定性控制
python·langchain·agent
weixin_446260856 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
我的xiaodoujiao6 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
qetfw6 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具
用户8356290780517 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
一次旅行7 小时前
Python+大模型端到端自动化日报系统
开发语言·python·自动化
天天爱吃肉82188 小时前
【电源拆解:跟着问答逐一认识开关适配器PCB元器件】
大数据·人工智能·python·功能测试·嵌入式硬件·汽车
_Jimmy_8 小时前
AI应用开发工程师面试题库
人工智能·python·深度学习·机器学习·知识图谱