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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章