使用fastapi的时候,swagger-ui.css 、swagger-ui-bundle.js、redoc.standalone.js 有时候无法加载(国内环境原因或者是局域网屏蔽),此时就需要自己用魔法下载好对应文件,然后替换到fastapi里面去。
fastapi里面依靠这2个函数实现docs和redoc:
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
fastapi里面官网给的解决办法:
https://github.com/tiangolo/fastapi/blob/ac93277d3b506f4076aee1af6ae5a86406f545c6/docs_src/custom_docs_ui/tutorial001.py#L4
实践起来就是,首先下载好这些文件:
其次复现出/docs路由和/redoc路由:
import os
import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_htmlapp = FastAPI(title='outpainting_captioning_upscaler',description='outpainting images, captioning images,upscaler images',version='1.0.0',docs_url=None,redoc_url=None, # 设置 ReDoc 文档的路径)
app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],
)
app.mount("/static", StaticFiles(directory="static"), name="static")@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():return get_swagger_ui_html(openapi_url="/openapi.json",title="xx",# oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,swagger_js_url='/static/swagger/swagger-ui-bundle.js',swagger_css_url='/static/swagger/swagger-ui.css',swagger_favicon_url='/static/swagger/img.png',)@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/swagger/redoc.standalone.js",)# 写个测试接口
@app.get('/xx')
async def test():return {'message': 'test success'}if __name__ == '__main__':uvicorn.run(f'{os.path.basename(__file__).split(".")[0]}:app',host='0.0.0.0',port=7777,reload=False,workers=1)
其中文件也可以去这里下载:
下载:https://wwsm.lanzouy.com/i682Q1frjnmd 密码:9zw2
成功: