I am trying to pass a nested dictionary as a parameter to a GET request, which is handled by a Flask worker. The whole setup is Nginx+Gunicorn+Flask. On the client, I am doing the following:
import requests
def find_cabin():
party = {'People' : [{'Age': 44, 'Gender': 'F', 'Habits': 'Smoking,Drinking'}, {'Age': 9, 'Gender': 'F'}
, {'Age': 4, 'Gender': 'F'}, {'Age': 49, 'Gender': 'M'}],
'Vehicles': [{'Make/Model': 'Honda Civic'}, {'Make/Model': 'Toyota RAV4'}],
'Must Haves':['Deck', 'Fireplace', 'Boat launch', {'Bedrooms': 2}]}
uri = 'mysite.com/find_cabin'
headers = {'Content-Type': 'application/json', 'Accept': 'text/plain'}
res = requests.get(uri, data=json.dumps(party), headers=headers)
return res.text
On the server, in my Flask handler, I am doing this:
@app.route('/find_cabin/', methods=['GET'])
def find_cabin():
payload = request.data
# payload is empty
print ('payload for find_cabin: ', payload)
#process request
The payload is empty. What am I missing? How should I pass complex nested structures to my Flask app?
Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).
Iterate over all values of a nested dictionary in python For a normal dictionary, we can just call the items() function of dictionary to get an iterable sequence of all key-value pairs.
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.
Key Points to Remember: Nested dictionary is an unordered collection of dictionary. Slicing Nested Dictionary is not possible. We can shrink or grow nested dictionary as need. Like Dictionary, it also has key and value.
The GET method does not have a body. Either encode your data as query parameters, or use a POST request. If you use POST, you can pass the data directly as JSON:
requests.post(url, json=party)
# within the view
party = request.get_json()
If you want to use GET you could just encode the JSON as query parameter.
requests.get(url, params={'party': json.dumps(party)})
# within the view
party = json.loads(request.args['party'])
You could also try to come up with some scheme to flatten a nested structure into query params, but this is not straightforward. Simple nesting could use '.' to separate paths, and lists could specify the key multiple times, but what if there is a nested list of nested objects?
This is not really a good use of query parameters, it would make more sense in this case to send a POST body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With