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

配置完再次访问

相关推荐
じ☆冷颜〃2 小时前
分布式系统中网络技术的演进与异构融合架构(HFNA)
笔记·python·物联网·设计模式·架构·云计算
夜思红尘4 小时前
算法--双指针
python·算法·剪枝
人工智能训练4 小时前
OpenEnler等Linux系统中安装git工具的方法
linux·运维·服务器·git·vscode·python·ubuntu
智航GIS5 小时前
8.2 面向对象
开发语言·python
蹦蹦跳跳真可爱5896 小时前
Python----大模型(GPT-2模型训练加速,训练策略)
人工智能·pytorch·python·gpt·embedding
xwill*6 小时前
π∗0.6: a VLA That Learns From Experience
人工智能·pytorch·python
还不秃顶的计科生6 小时前
LeetCode 热题 100第二题:字母易位词分组python版本
linux·python·leetcode
weixin_462446237 小时前
exo + tinygrad:Linux 节点设备能力自动探测(NVIDIA / AMD / CPU 安全兜底)
linux·运维·python·安全
不瘦80斤不改名7 小时前
Python 日志(logging)全解析
服务器·python·php
多米Domi0117 小时前
0x3f 第19天 javase黑马81-87 ,三更1-23 hot100子串
python·算法·leetcode·散列表