如何使用requests.post(Python)发送数组?"值错误:解压缩的值太多"

Bob*_*sta 46 python api python-requests

我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)

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

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}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 69

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

请记住 - 所有帖子主体必须是JSON编码数据(无表格数据).

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)
Run Code Online (Sandbox Code Playgroud)

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

  • 造成比data = json.dumps(payload)更少的麻烦.谢谢你的解决方案 (4认同)
  • 呸! 非常简单,我在扫描文档时以某种方式错过了它。非常感谢。 (2认同)

ela*_*ver 17

好吧,事实证明我需要做的就是添加这些标题:

headers = {'Content-Type': 'application/json', 'Accept':'application/json'}
Run Code Online (Sandbox Code Playgroud)

然后调用请求

requests.post(url,data=json.dumps(payload), headers=headers)
Run Code Online (Sandbox Code Playgroud)

现在我很好!


MHB*_*HBN 5

切记在HTTP POST请求中发送数组(列表)字典时,请在post函数中使用json参数并将其值设置为array(list)/ dictionary

在您的情况下,它将像:

r = request.post(URL,headers = headers,json = data)

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

快速入门介绍,请参阅Python中的API集成

  • 谢谢你!现在,每当在 POST 请求中发送列表或字典时,我都会记得使用 JSON 参数! (2认同)