在Python请求数据中包含列表

时间:2014-03-30 20:54:13

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

我使用请求库将PUT数据发送到Pipeline Deals API,数据要求我为请求data中的值设置列表。

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

这就是我PUT数据的方式:

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

我该怎么做?

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:0)

如果你想要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