[英]How to send an array using requests.post (Python)? "Value Error: Too many values to unpack"
我正在尝试使用 requests.post 向 WheniWork API 发送请求数组(列表),但我不断收到两个错误之一。 当我将列表作为列表发送时,我收到一个解包错误,当我将它作为一个字符串发送时,我收到一个错误,要求我提交一个数组。 我认为这与请求处理列表的方式有关。 以下是示例:
url='https://api.wheniwork.com/2/batch'
headers={"W-Token": "Ilovemyboss"}
data=[{'url': '/rest/shifts', 'params': {'user_id': 0,'other_stuff':'value'}, 'method':'post',{'url': '/rest/shifts', 'params': {'user_id': 1,'other_stuff':'value'}, 'method':'post'}]
r = requests.post(url, headers=headers,data=data)
print r.text
# ValueError: too many values to unpack
简单地将数据的值括在引号中:
url='https://api.wheniwork.com/2/batch'
headers={"W-Token": "Ilovemyboss"}
data="[]" #removed the data here to emphasize that the only change is the quotes
r = requests.post(url, headers=headers,data=data)
print r.text
#{"error":"Please include an array of requests to make.","code":5000}
您想传入JSON 编码的数据。 请参阅API 文档:
请记住——所有帖子正文必须是 JSON 编码的数据(无表单数据)。
requests
库使这变得非常简单:
headers = {"W-Token": "Ilovemyboss"}
data = [
{
'url': '/rest/shifts',
'params': {'user_id': 0, 'other_stuff': 'value'},
'method': 'post',
},
{
'url': '/rest/shifts',
'params': {'user_id': 1,'other_stuff': 'value'},
'method':'post',
},
]
requests.post(url, json=data, headers=headers)
通过使用json
关键字参数,数据会为您编码为 JSON,并且Content-Type
标头设置为application/json
。
好吧,事实证明我需要做的就是添加这些标题:
headers = {'Content-Type': 'application/json', 'Accept':'application/json'}
然后调用请求
requests.post(url,data=json.dumps(payload), headers=headers)
现在我很好!
始终记住在HTTP POST请求中发送数组(列表)或字典时,请在 post 函数中使用json 参数并将其值设置为您的数组(列表)/字典。
在您的情况下,它将类似于:
r = requests.post(url, headers=headers, json=data)
注意: POST 请求将 body 参数的内容类型隐式转换为 application/json。
我有一个类似的案例但完全不同的解决方案,我复制了一段代码,如下所示:
resp_status, resp_data = requests.post(url, headers=headers,
json=payload, verify=False)
这导致错误:
ValueError: too many values to unpack (expected 2)
只需分配给一个变量即可解决问题:
response = requests.post(url, headers=headers,
json=payload, verify=False)
下面为我工作。
res = requests.post(url, headers=headers, json=data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.