Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending POST request with multiples values for same key with requests library

How would you go about sending a request with multiples values with the same key?

r = requests.post('http://www.httpbin.org/post', data={1: [2, 3]})
print r.content
{
  ...
  "form": {
    "1": "3"
  }, 
  ...
}

Edit:

Hmm, very odd. I tried echoing the post data using a simple Flask application and I'm getting:

[('1', u'2'), ('1', u'3')]

Is this just a shortcoming of httpbin.org?

like image 704
Acorn Avatar asked Dec 06 '11 01:12

Acorn


2 Answers

Try the Werkzeug MultiDict. It's the same structure used for this purpose in Flask applications.

import requests
from werkzeug.datastructures import MultiDict

data = MultiDict([('1', '2'), ('1', '3')])
r = requests.post('http://www.httpbin.org/post', data=data)
print(r.content)

Result:

...
"form": {
  "1": [
    "2",
    "3"
  ]
},
...
like image 89
robots.jpg Avatar answered Oct 01 '22 18:10

robots.jpg


It turns out that requests was sending the POST data without a problem. It was an issue on the http://httpbin.org end that was causing form data to be flattened, and multiple values with the same key to be ignored.

like image 34
Acorn Avatar answered Oct 01 '22 19:10

Acorn