【问题标题】:How to programmatically instantiate Starlette's Request with a body?如何用正文以编程方式实例化 Starlette 的请求?
【发布时间】:2020-09-25 14:03:40
【问题描述】:

我有一个项目,其中包含一些使用 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() 将其转换为 python dict。

现在,我需要在另一个函数中调用insert_tab,所以我需要以某种方式从Starlette 实例化Request 对象。我以前做过,但没有 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 对象,但我找不到这样做的方法。

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

【问题讨论】:

  • 更好的设计是编写一个处理原始 Python dict 的函数,然后从 API 函数中使用 request.json() 调用该函数,并直接从“其他函数”中调用它。通常,您不想在代码中的其他地方调用依赖于 Request 之类的 API 函数,除非您正在为 API 编写测试(在这种情况下,有一些方法可以创建“模拟请求”以进行测试)目的)。

标签: python fastapi starlette


【解决方案1】:

如果您尝试从应用程序中以编程方式调用另一个端点,最好跳过 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

【讨论】:

    【解决方案2】:

    我不是 ASGI 和 HTTP 请求方面的专家,但这里有一种方法可以让它发挥作用。


    要创建带有请求正文的Request 对象,您可以传入receive 参数:

    # starlette/requests.py
    
    class Request(HTTPConnection):
        def __init__(
            self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send
        ):
    

    其中receive 的类型为Receive:

    # starlette/types.py
    
    Message = typing.MutableMapping[str, typing.Any]
    Receive = typing.Callable[[], typing.Awaitable[Message]]
    

    这是一种awaitable 函数,它返回一个Message,这是一种可变映射(例如dict)。 receive 是一个函数的原因是因为它是“接收”通道的一部分,预计会出现在 "receive" the request body as a stream of messages:

    关于传入请求的大部分信息都存储在“范围”中,并在 ASGI 应用程序实例化时呈现。但是,对于请求正文,这是不可能的。

    为了访问请求正文,我们必须从“接收”通道获取消息流。

    您可以从 Starlette 的请求代码中看到它是如何使用的:

    self._stream_consumed = True
    while True:
        message = await self._receive()  # <------------- this.
        if message["type"] == "http.request":
            body = message.get("body", b"")
            if body:
                yield body
            if not message.get("more_body", False):
                break
        elif message["type"] == "http.disconnect":
            self._is_disconnected = True
            raise ClientDisconnect()
    yield b""
    

    由于您可能已经准备好请求正文,因此您可以将其假流成一个块,同时考虑到 "type"、"body"(实际的正文/有效负载)和 @987654338 的预期键@ 键设置为False 以跳出流。

    import json
    from starlette.requests import Message
    
    async def create_body() -> Message:
        body = {'abc': 123, 'def': {'ghi': 456}}
        return {
            'type': 'http.request',
            'body': json.dumps(body).encode('utf-8'),
            'more_body': False,
        }
    

    然后您可以将其传递给Request 的receive= 参数以调用您的函数:

    from starlette.requests import Request
    
    @router.put('/tab/{tab_name}')
    async def insert_tab(request: Request, tab_name: str):
        tab = await request.json()
        return {tab_name: tab}
    
    @router.put('/call-insert-tab')
    async def some_other_function():
        req = Request(
            scope={
                'type': 'http',
                'scheme': 'http',
                'method': 'PUT',
                'path': '/tab/abc',
                'raw_path': b'/tab/abc',
                'query_string': b'',
                'headers': {}
            },
            receive=create_body,  # <-------- Pass it here
        )
        return await insert_tab(req, 'abc')
    

    虽然可以工作,但我会说它不是伟大。使用像 Starlette 这样的库的目的是不去关心这些 HTTP 请求对象是如何实际创建和处理的。除了示例之外,我没有测试上面的代码,但我觉得它可能会在某些时候中断(尤其是使用 FastAPI 的依赖注入)。

    因为您的用例只是为了

    发送一个包含新标签数据的json作为我的请求的主体,稍后将使用await request.json()将其转换为python dict

    您实际上不需要为此直接使用Request。我的建议是用 tab: Tab 模型替换您的 request: Request 参数,如有关传入请求正文的 FastAPI 教程中所述:https://fastapi.tiangolo.com/tutorial/body/

    from pydantic import BaseModel
    
    class Tab(BaseModel):
        abc: int
        xyz: int
    
    @app.put('/tab/{tab_name}')
    async def insert_tab(tab: Tab, tab_name: str):
        print(tab.abc)
        print(tab.xyz)
        return {tab_name: tab}
    

    FastAPI 将自动获取底层 Request 对象的主体,并将其从 JSON 转换为您的模型。 (它自动假定不在路径中的参数是主体/有效负载的一部分。)。它应该和request.json()一样工作:

    $ cat data.json
    {
        "abc": 123,
        "xyz": 456
    }
    
    $ curl -s -XPUT 'http://localhost:5050/tab/tab1' --header 'Content-Type: application/json' --data @data.json | jq
    {
      "tab1": {
        "abc": 123,
        "xyz": 456
      }
    }
    

    这也将使调用需要请求正文的路由函数更容易:您只需要直接传入数据而无需打扰Requests:

    @app.put('/tab/{tab_name}')
    async def insert_tab(tab: Tab, tab_name: str):
        return {tab_name: tab}
    
    @app.put('/call-insert-tab')
    async def some_other_function():
        tab = Tab(abc=123, xyz=456)
        return await insert_tab(tab, 'tab1')
    

    有关更多信息和示例,请参阅FastAPI tutorial on Request Body。如果你想避免 Pydantic 或者出于某种原因不想为 body 创建类,还有一个 Body 类型参数:https://fastapi.tiangolo.com/tutorial/body-multiple-params/#singular-values-in-body。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 2017-01-26
      相关资源
      最近更新 更多