【问题标题】:How to handle JSON request body with the Starlette framework如何使用 Starlette 框架处理 JSON 请求正文
【发布时间】:2020-09-26 18:52:54
【问题描述】:

我正在将我的 API 框架从旧版本的 ApiStar 移动到 Starlette,并且在我路由到的函数中无法正确访问 HTTP 主体,在这种情况下,它是 JSON 有效负载。

这就是使用 ApiStar 对我有用的东西:

from apistar import http
import json

def my_controller(body: http.Body):

    spec = json.loads(body)

    print(spec['my_key_1'])
    print(spec['my_key_2'])

任何基本上将上述内容转换为 Starlett 使用的语法的帮助都会非常有帮助,因为我无法从文档中弄清楚。

谢谢!

【问题讨论】:

    标签: python-3.x rest payload starlette


    【解决方案1】:

    Starlette tests 有一个从请求中读取 JSON 的示例。

        async def app(scope, receive, send):
            request = Request(scope)
            try:
                data = await request.json()
                print(data['my_key_1'])
            except RuntimeError:
                data = "Receive channel not available"
            response = JSONResponse({"json": data})
            await response(scope, receive, send)
    

    【讨论】:

    【解决方案2】:

    例如

    async def user_login(request: Request) -> JSONResponse:
    
        try:
            payload = await request.json()
        except JSONDecodeError:
            sprint_f('cannot_parse_request_body', 'red')
            raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="cannot_parse_request_body")
        email = payload['email']
        password = payload['password']
    

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 1970-01-01
      • 2016-05-09
      • 2019-03-13
      • 2013-12-21
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      相关资源
      最近更新 更多