【问题标题】:How to unmarshall incoming request payload as method/function arguments based on content type in Python flask or bottle frameworks如何根据 Python 烧瓶或瓶框架中的内容类型将传入的请求有效负载解组为方法/函数参数
【发布时间】:2018-07-26 18:12:45
【问题描述】:

是否可以将传入的请求负载解组为瓶子或烧瓶中的方法/函数参数?如果有,怎么做?

我想发送以下内容作为 POST/PUT 请求的请求负载,

{ 'foo': [ 'bar1', 'bar2'], 'spam': 2 }

并在伪代码中使用它,

@route('/cheeseshop/<id>', method='PUT')
def cheeseShop(foo, spam):
    pass

这可以通过查看这些框架中的内容类型自动完成吗?

【问题讨论】:

    标签: python rest flask content-type bottle


    【解决方案1】:

    为了代码的可读性,这样做有一些注意事项,但可能的解决方案如下。

    定义序列化方法。如果您需要与不同的客户合作,我建议JSON

    创建一个装饰器并将它放在你的functionroute之间

    @route(...)
    @expandargs
    def foo(id, bar, baz):
        ...
    

    在装饰器中使用request.json()(如果是JSON,则自动解码有效负载)来扩展args,然后您将使用原始args和新的**expandedargs调用包装函数(注意双星号来展开关键字)。

    混合位置和关键字参数时会出现问题。

    【讨论】:

    • 谢谢 - 我明白你的意思了。我认为这些框架中可能有一些我找不到的东西。
    【解决方案2】:

    这是因为只是勾勒出 Paolos 的答案,但为了帮助其他人寻找这个,这里有一个实现目标的解组装饰器示例。

    from functools import wraps
    def unmarshal_payload(view):
        @wraps(view)
        def unmashalled_view(*args, **kwargs):
            return view(*args, **request.get_json(), **kwargs)
        return unmashalled_view 
    

    然后将用作:

    @app.route(f'/<int:id>/', methods=['PUT'])
    @unmarshal_payload
    def view(id, foo, bar):
        print(id, foo, bar)
        return 'Success'
    

    然后根据您想要如何处理包含{'id': 'something'} 的有效负载之类的内容,您可以更改它。就像在这个幼稚的实现中一样,Flask 将返回一个内部服务器错误,因为 python 会抛出一个 TypeError,因为函数接收同一关键字的多个关键字参数。此外,如果您提供未在视图中命名的参数,则会收到带有 Unexpected 关键字的类型错误。

    所以稍微宽松一点的定义是:

    from functools import wraps
    def unmarshal_payload(view):
        @wraps(view)
        def unmashalled_view(*args, **kwargs):
            return view(*args, **kwargs, **{k:v for k,v in request.get_json().items() if k not in kwargs})
        return unmashalled_view 
    
    @app.route(f'/<int:id>/', methods=['PUT'])
    @unmarshal_payload
    def view(id, foo, bar, **kwargs):
        print(id, foo, bar)
        return 'Success'
    

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      相关资源
      最近更新 更多