zoukankan      html  css  js  c++  java
  • FastAPI实战:简易MockServe

    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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    mysql常用技能分享
    php生成器使用总结
    MySQL索引使用方法和性能优化
    servlet相关
    UML图
    How Tomcat Works
    字符串编码
    高效工作
    php 设计模式总结
    python之装饰器
  • 原文地址:https://www.cnblogs.com/zy7y/p/15102770.html
Copyright © 2011-2022 走看看