如何使用 requests.post (Python)发送数组? “ Value Error: Too many Value 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}
110034 次浏览

Well, It turns out that all I needed to do was add these headers:

headers = {'Content-Type': 'application/json', 'Accept':'application/json'}

and then call requests

requests.post(url,data=json.dumps(payload), headers=headers)

and now i'm good!

You want to pass in JSON encoded data. See the API documentation:

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

The requests library makes this trivially easy:

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)

By using the json keyword argument the data is encoded to JSON for you, and the Content-Type header is set to application/json.

Always remember when sending an array(list) or dictionary in the HTTP POST request, do use json argument in the post function and set its value to your array(list)/dictionary.

In your case it will be like:

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

Note: POST requests implicitly convert parameter's content type for body to application/json.

For a quick intro read API-Integration-In-Python

I have a similar case but totally different solution, I've copied a snippet of code which looks like that:

resp_status, resp_data = requests.post(url, headers=headers, json=payload, verify=False)

and this resulted in error:

ValueError: too many values to unpack (expected 2)

just assigning to one variable resolve the issue:

response = requests.post(url, headers=headers, json=payload, verify=False)