Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to post multiple value with same key in python requests?

requests.post(url, data={'interests':'football','interests':'basketball'}) 

I tried this, but it is not working. How would I post football and basketball in the interests field?

like image 459
Jasonyi Avatar asked Apr 30 '14 09:04

Jasonyi


People also ask

How do you pass multiple parameters in a post request in python?

Multiple Parameters In the above URL, '&' should be followed by a parameter such as &ie=UTF-8. In this parameter, i.e., is the key and, UTF-8 is the key-value. Enter the same URL in the Postman text field; you will get the multiple parameters in the Params tab.

How do you send multiple requests in python?

There are two basic ways to generate concurrent HTTP requests: via multiple threads or via async programming. In multi-threaded approach, each request is handled by a specific thread. In asynchronous programming, there is (usually) one thread and an event loop, which periodically checks for the completion of a task.


2 Answers

Dictionary keys must be unique, you can't repeat them. You'd use a sequence of key-value tuples instead, and pass this to data:

requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')]) 

Alternatively, make the values of the data dictionary lists; each value in the list is used as a separate parameter entry:

requests.post(url, data={'interests': ['football', 'basketball']}) 

Demo POST to http://httpbin.org:

>>> import requests >>> url = 'http://httpbin.org/post' >>> r = requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')]) >>> r.request.body 'interests=football&interests=basketball' >>> r.json()['form'] {u'interests': [u'football', u'basketball']} >>> r = requests.post(url, data={'interests': ['football', 'basketball']}) >>> r.request.body 'interests=football&interests=basketball' >>> r.json()['form'] {u'interests': [u'football', u'basketball']} 
like image 133
Martijn Pieters Avatar answered Sep 20 '22 15:09

Martijn Pieters


It is possible to use urllib3._collections.HTTPHeaderDict as a dictionary that has multiple values under a key:

from urllib3._collections import HTTPHeaderDict data = HTTPHeaderDict() data.add('interests', 'football') data.add('interests', 'basketball') requests.post(url, data=data) 
like image 20
Sjoerd Avatar answered Sep 21 '22 15:09

Sjoerd