使用fastapi的时候,swagger-ui.css 、swagger-ui-bundle.js、redoc.standalone.js 有时候无法加载(国内环境原因或者是局域网屏蔽),此时就需要自己用魔法下载好对应文件,然后替换到fastapi里面去。
fastapi里面依靠这2个函数实现docs和redoc:
bash展开代码from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
fastapi里面官网给的解决办法:
实践起来就是,首先下载好这些文件:

其次复现出/docs路由和/redoc路由:
python展开代码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_html
app = 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)
其中文件也可以去这里下载:
bash展开代码下载:https://wwsm.lanzouy.com/i682Q1frjnmd 密码:9zw2
成功:



本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!