fastapi 使用本地靜態檔案替換 swagger cdn

ponponon發表於2022-05-17

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 資料夾:

圖片.png

這三個檔案的下載地址:

redoc.standalone.js 沒有找到下載地址

這裡的下載地址都是非 cdn.jsdelivr.net 的地址

參考文章:
FastApi教程|擴充套件OpenAPI
download-the-files

相關文章