如何使用 requests.post (Python) 发送数组?“值错误:解包的值太多" [英] How to send an array using requests.post (Python)? "Value Error: Too many values to unpack"

查看:29
本文介绍了如何使用 requests.post (Python) 发送数组?“值错误:解包的值太多"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 requests.post 向 WheniWork API 发送请求数组(列表),但我不断收到两个错误之一.当我将列表作为列表发送时,我收到一个解包错误,当我将它作为一个字符串发送时,我收到一个错误,要求我提交一个数组.我认为这与请求处理列表的方式有关.以下是示例:

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:

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}

推荐答案

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

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

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

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

requests 库使这变得非常简单:

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)

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

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

这篇关于如何使用 requests.post (Python) 发送数组?“值错误:解包的值太多"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆