Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the value of nested dict in Immutabledict sent via request of werkzeug(flask)?

I asked question in past, but still facing the problem. 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.

like image 929
kinakomochi Avatar asked Dec 16 '12 08:12

kinakomochi


People also ask

How do I access nested dict values?

Access Nested Dictionary Items You can access individual items in a nested dictionary by specifying key in multiple square brackets. If you refer to a key that is not in the nested dictionary, an exception is raised. To avoid such exception, you can use the special dictionary get() method.

What is ImmutableMultiDict?

In this article, we will see how to get data from ImmutableMultiDict in the flask. It is a type of Dictionary in which a single key can have different values. It is used because some elements have multiple values for the same key and it saves the multiple values of a key in form of a list.


1 Answers

You're sending complex nested data structure as HTML form, it won't work like you expect. Encode it as JSON:

import json
import requests

url = 'http://example.com/'
payload = {"address": {"US": "San Francisco", "UK": "London", "CH": "Shanghai"}}
data = json.dumps(payload)
headers = {'Content-Type': 'application/json'}
requests.post(url, data=data, headers=headers)

In you Flask app it would be accesible via request.json (already decoded).

like image 74
Audrius Kažukauskas Avatar answered Nov 15 '22 10:11

Audrius Kažukauskas