FastAPI实战:简易MockServe

Mock

我个人理解就是为了伪造返回结果的东西,MockServe通常说的就是接口未开放完成但是现在需要调用,所以无论是通过转发还是直接访问这个url,其结果基本就是自己定义的 当然做仔细点就是 给个类型其自动生成对应类型数据

预览图

FastAPI实战:简易MockServe

使用技术栈

FastAPI + tortoise-orm + sqlite3

实现原理

Path参数实现,用户访问时如果这个Path参数存在数据库,对应请求方法也是对的那么就可以访问

核心代码

方法一:个人最开始实现的方法

async def mock(request: Request, url: str = Path(...)):
    try:
        mocks = await models.MockApi.filter(path=url, status=True).first()
        return mocks.body if mocks.method.upper() == request.method else ServeNotFount()
    except Exception as e:
        return ServeNotFount()

app.add_api_route(
    "/mock/{url}",
    endpoint=mock,
    methods=[
        "post",
        "get",
        "delete",
        "put"],
    include_in_schema=False
)

方法二,https://gitee.com/ran_yong 纠正 @app.api_route

@app.api_route("/mock/{url}", methods=["post", "get", "delete", "put"], include_in_schema=False)
async def mock(request: Request, url: str = Path(...)):
    try:
        mocks = await models.MockApi.filter(path=url, status=True, method=request.method.lower()).first()
        return mocks.body
    except Exception as e:
        return ServeNotFount()

视频说明

源码地址

Gitee: https://gitee.com/zy7y/FastAPIMockServe.git
Github: https://github.com/zy7y/FastAPIMockServe

FastAPI实战:简易MockServe

上一篇:【GCC编译器】Swing Modulo Scheduling


下一篇:Windows 8 应用开发与Windows Phone的几个重要不同