首页 > 解决方案 > 如何用正文以编程方式实例化 Starlette 的请求?

问题描述

我有一个项目,其中包含一些使用 FastAPI 的 API,我需要在项目中调用其中一个 API 函数。使用 FastAPI 和 Starlette 的 API 函数如下所示

@router.put("/tab/{tab_name}", tags=["Tab CRUD"])
async def insert_tab(request: Request, tab_name: str):
    tab = await request.json()
    new_tab_name = tab["name"]
    new_tab_title = tab["title"]
    # Rest of the code

我发送一个包含新选项卡数据的 JSON 作为我的请求的主体,稍后将使用await request.json().

现在,我需要调用insert_tab另一个函数,所以我需要以某种方式RequestStarlette实例化对象。我以前做过,但没有 JSON 正文:

from starlette.requests import Request
from starlette.datastructures import Headers

headers = Headers()
scope = {
    'method': 'GET',
    'type': 'http',
    'headers': headers
}
request = Request(scope=scope)

但在这种情况下,我还需要将 JSON 主体注入到Request对象中,但我找不到这样做的方法。

有没有人这样做过或知道我该怎么做?

标签: pythonfastapistarlette

解决方案


如果您尝试从应用程序中以编程方式调用另一个端点,最好跳过 HTTP 层并直接调用底层函数。

但是,如果您在尝试构建用于单元测试的模拟请求时进入此页面,这里有一个包含标头的示例:

from starlette.requests import Request
from starlette.datastructures import Headers
from typing import Dict


def build_request(headers: Dict = None) -> Request:
    if headers is None:
        headers = {}
    return Request({
        "type": "http",
        "headers": Headers(headers).raw
    })

有关使用 Starlette 的 ASGI 请求对象的更多信息:
https ://www.encode.io/articles/working-with-http-requests-in-asgi


推荐阅读