关于python:fastapi-使用本地静态文件替换-swagger-cdn

52次阅读

共计 2081 个字符,预计需要花费 6 分钟才能阅读完成。

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 文件夹:

这三个文件的下载地址:

  • swagger-ui-bundle.js
  • swagger-ui.css

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

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

正文完
 0