【问题标题】:Include list in Python request data在 Python 请求数据中包含列表
【发布时间】:2014-03-30 20:54:13
【问题描述】:

我正在使用 Requests 库将 PUT 数据发送到 Pipeline Deals API,并且数据要求我在请求 data 中为值添加一个列表。

他们的例子:"custom_label_83": [ 28, 29 ]

这就是我 PUTting 数据的方式:

requests.put("https://www.pipelinedeals.com/...", data={'custom_label_83': [28,29]})

问题似乎是当我PUT那个例子时,我最终只有29PUT,因为请求的主体(编码后)是这样的:

custom_label_83%5D=28&custom_fields%5D%5Bcustom_label_83%5D=29

因此,该字段设置了两次,最终结果为29,而不是同时包含2829 的列表。我希望PUT 请求的正文是这样的:

custom_label_83%5D=28,29

我该怎么做?

【问题讨论】:

    标签: python http python-2.7 python-requests url-encoding


    【解决方案1】:

    您遇到的行为(多个 GET 参数)的原因是当您将列表作为 params 字典中的键的值传递时默认的 requests 行为。

    如果您希望输出为custom_label_83%5D=28,29,则必须加入列表的值:

    >>> ','.join(map(str, [28, 29]))
    '28,29'
    

    【讨论】:

    • 谢谢!这正是我想要的。由于某种原因,API 在这里仍然无法正常工作,但此代码符合要求。
    • 事实证明(至少对于管道交易而言),这是正确的语法:data = {'some_custom_label[]': 'some value'}。标签末尾的[] 表示它是一个数组。
    • @br1ckb0t 很高兴你把它整理好了。
    【解决方案2】:

    如果您希望 28 和 29 在一起,则必须以某种方式将它们组合到所需的列表中。您可以使用字符串、嵌套列表、嵌套元组等...

    "custom_label_83": [ '28,29' ] #string example
    
    "custom_label_83": [ [28,29] ] #nested list example
    
    "custom_label_83": [ (28,29) ] #nested tuple example
    

    【讨论】:

      猜你喜欢
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 2014-06-16
      • 2017-02-24
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多