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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31168819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:35:46  来源:igfitidea点击:

How to send an array using requests.post (Python)? "Value Error: Too many values to unpack"

pythonapipython-requests

提问by Bobby Battista

I'm trying to send an array(list) of requests to the WheniWork API using requests.post, and I keep getting one of two errors. When I send the list as a list, I get an unpacking error, and when I send it as a string, I get an error asking me to submit an array. I think it has something to do with how requests handles lists. Here are the examples:

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

Simply wrapping the value for data in quotes:

只需将数据的值括在引号中:

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}

回答by elad silver

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!

现在我很好!

回答by Martijn Pieters

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

您想传入JSON 编码的数据。请参阅API 文档

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

请记住——所有帖子正文必须是 JSON 编码的数据(无表单数据)。

The requestslibrary makes this trivially easy:

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)

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

通过使用json关键字参数,数据会为您编码为 JSON,并且Content-Type标头设置为application/json.

回答by MHBN

Always remember when sending an array(list)or dictionaryin the HTTP POSTrequest, do use json argumentin the post function and set its value to your array(list)/dictionary.

始终记住在HTTP POST请求中发送数组(列表)字典时,请在 post 函数中使用json 参数并将其值设置为您的数组(列表)/字典

In your case it will be like:

在您的情况下,它将类似于:

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

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

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

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

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

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

回答by Michal Lis

I have a similar case but totally different solution, I've copied a snipped 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)