Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

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}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...