如何使用requests.post(Python)发送数组值错误:要解包的值太多“

2024-09-26 04:52:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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}

Tags: thetohttpsapiurl列表data错误
3条回答

您需要传入JSON编码的数据。请参见API documentation

Remember — All post bodies must be JSON encoded data (no form data).

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请求中的数组(list)字典时,请务必记住在POST函数中使用json参数并将其值设置为数组(list)/dictionary

在你的情况下会是:

r = requests.post(url, headers=headers, json=data)

注意:POST请求隐式地将body的参数内容类型转换为application/json。

快速介绍阅读API-Integration-In-Python

相关问题 更多 >