How to pass a nested dictionary to Flask's GET request handler

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

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?

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!