fastapi 使用本地静态文件替换 swagger cdn

发布时间:2023-11-13 10:00

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


邪恶长城屏蔽了 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 文件夹:

\"fastapi

这三个文件的下载地址:

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

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

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号