SEO optimization:
FastAPI: The solution for the docs document cannot be loaded
The fastapi swagger document often fails to open
The fastapi swagger document has not been displayed and has been loading
js and css load timeout for fastapi swagger documentation
The cdn of the js and css of the fastapi swagger document cannot be opened by the wall cdn.jsdelivr
cdn.jsdelivr connection timed out
cdn.jsdelivr cannot be accessed
cdn.jsdelivr is blocked
The Great Wall of Evil has blocked the jsdelivr
, so domestic users cannot access it, which is the reason for the poor experience of the fastapi
swagger
document document:
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
Solution?
Use the following code:
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'
Note two points:
-
app = FastAPI(docs_url=None, redoc_url=None)
these two should be None - (forget)
My static file structure:
A static swagger-ui
folder is created below:
The download address of these three files:
redoc.standalone.js
No download address found
The download addresses here are all non cdn.jsdelivr.net
addresses
Reference article:
FastApi Tutorial | Extending OpenAPI
download-the-files
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。