address_dict = {'address': {'US': 'San Francisco', 'US': 'New York', 'UK': 'London'}}
When above parameters was sent via requests, how can I get values in address key using request.form on Flask?
import requests
url = 'http://example.com'
params = {"address": {"US": "San Francisco", "UK": "London", "CH": "Shanghai"}}
requests.post(url, data=params)
Then I got this in context of flask.request.
ImmutableMultiDict([('address', u'US'), ('address', 'US'), ('address', 'UK')])
How can I get the value in each key of addresses?
Thanks.
for example like this:
from werkzeug.datastructures import ImmutableMultiDict
imd = ImmutableMultiDict([('address', u'US'), ('address', 'US'), ('address', 'UK')])
print imd.getlist('address')
prints:
[u'US', 'US', 'UK']
edit:
Your POST-request is sent application/x-www-form-urlencoded
, which means as combination as key/value pairs. It doesn't support a nested dict structure directly. When i try your curl-request I get this:
ImmutableMultiDict([('address[US]', u'San Francisco'), ('address[US]', u'New York'), ('address[UK]', u'London')])
so the keys are interpreted literally here.
and using urllib2
i get this result:
>>> print urllib2.urlopen("http://localhost:5000/post", data=urllib.urlencode(address_dict)).read()
ImmutableMultiDict([('address', u"{'UK': 'London', 'US': 'New York'}")])
here urlencode
simply sends a string representation of the inner dict.
and finally using requests
:
>>> print requests.post("http://localhost:5000/post", data=address_dict).content
ImmutableMultiDict([('address', u'UK'), ('address', u'US')])
here the array is flattened and recurring keys eliminated.
There is simply no defined way how to send a nested dict like yours in an urlencoded way, so you'll have to find another solution.