• 周五. 4月 19th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

FastAPI实战:简易MockServe

admin

11月 28, 2021

Mock

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

预览图

使用技术栈

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

作者:zy7y
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注