继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

局域网环境生成fastapi接口文档的方法

全栈测试之路
关注TA
已关注
手记 19
粉丝 1
获赞 3

fastapi自动生成的接口文档,基于Swagger UI, 但是在内部局域网环境无法访问cdn,因此无法自动生成docs接口文档.

如果要在内网环境生成docs接口文档,需要修改示例代码如下:

from fastapi import FastAPI
import os
from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)
from fastapi.staticfiles import StaticFiles

app = FastAPI(docs_url=None, redoc_url=None)


root = os.path.abspath(os.path.join(os.path.basename(__file__), "../.."))
print(root)

app.mount("/static", StaticFiles(directory=f"{root}/static"), name="static")


@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="/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",
    )


@app.get(
    "/users/{username}",
    tags=["test"],
    name="TESTROUTER",
    description="TESTROUTER",
)
async def read_user(username: str):
    return {"message": f"Hello {username}"}


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8000)

> 注: 需要把 swagger-ui.cssswagger-ui-bundle.js 放到static文件夹下, 此文件夹放在上面示例代码的上一级目录下.

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP