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

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

问题描述

我正在尝试使用request.post将请求数组(列表)发送到WhileiWork 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.

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

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