2

seo优化:
FastAPI:docs文档无法加载的解决办法
fastapi swagger 文档的经常打不开
fastapi swagger 文档一直显示不出来,一直在加载中
fastapi swagger 文档的 js 和 css 加载超时
fastapi swagger 文档的 js 和 css 的 cdn 被墙
打不开 cdn.jsdelivr
cdn.jsdelivr 连接超时
cdn.jsdelivr 无法访问
cdn.jsdelivr 被墙了


邪恶长城屏蔽了 jsdelivr cdn ,所以导致国内的用户无法访问,才是导致 fastapiswagger 文档文档体验糟糕的原因:

https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui-bundle.js
https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui.css
https://cdn.jsdelivr.net/npm/redoc@latest/bundles/redoc.standalone.js

解决办法?

用下面的代码:
api.py

import uvicorn
from fastapi import FastAPI, File, Form, UploadFile
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)
import settings
from mark import BASE_DIR

app = FastAPI(docs_url=None, redoc_url=None)

app.mount('/static', StaticFiles(directory=BASE_DIR /
          'static'/'swagger-ui'), name='static')


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=app.title + " - Swagger UI",
        oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        # swagger_js_url=BASE_DIR/'static'/'swagger-ui'/'swagger-ui-bundle.js',
        # swagger_css_url=BASE_DIR/'static'/'swagger-ui'/'swagger-ui.css',
        swagger_js_url="/static/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui.css",
    )


@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
    return get_swagger_ui_oauth2_redirect_html()


@app.get("/redoc", include_in_schema=False)
async def redoc_html():
    return get_redoc_html(
        openapi_url=app.openapi_url,
        title=app.title + " - ReDoc",
        redoc_js_url="/static/redoc.standalone.js",
    )


if __name__ == "__main__":

    uvicorn.run(
        app='api:app',
        host="0.0.0.0",
        port=8000,
    )

mark.py

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent

MEDIA_PATH = BASE_DIR/'media'

注意有两个点:

  • app = FastAPI(docs_url=None, redoc_url=None) 这两个要为 None
  • (忘了)

我的静态文件结构:

static 下面建立了一个 swagger-ui 文件夹:

图片.png

这三个文件的下载地址:

redoc.standalone.js 没有找到下载地址

这里的下载地址都是非 cdn.jsdelivr.net 的地址

参考文章:
FastApi教程|扩展OpenAPI
download-the-files


universe_king
3.4k 声望678 粉丝