How to get data from 'ImmutableMultiDict' in flask

How to get data from 'ImmutableMultiDict' in flask

In Flask, form data submitted via POST or PUT requests, or the parameters of a GET request, are often available as an ImmutableMultiDict. This is a subclass of MultiDict, which is a dictionary that can have multiple values for the same key.

Here's how you can access data from an ImmutableMultiDict:

  1. Single Value for a Key: To get a single value for a given key, you use the get method. This is useful when you're expecting only one value for a key.

    value = request.args.get('key') # For query string (GET request) value = request.form.get('key') # For form data (POST/PUT request) 
  2. List of Values for a Key: If there are multiple values for a key and you want all of them, use the getlist method.

    values_list = request.args.getlist('key') # For query string (GET request) values_list = request.form.getlist('key') # For form data (POST/PUT request) 
  3. Access All Items: To get all the keys and values, you can use the to_dict method, which will give you a regular dictionary. If flat=False is passed, you get a dictionary where each key has a list of values.

    args_dict = request.args.to_dict() # Defaults to flat=True, giving the first value for each key form_dict = request.form.to_dict() # Same as above for form data # To get all values for each key in a list: args_dict_full = request.args.to_dict(flat=False) form_dict_full = request.form.to_dict(flat=False) 

Here is a full example using a Flask route that handles form data:

from flask import Flask, request app = Flask(__name__) @app.route('/submit', methods=['POST']) def submit(): # request.form is an ImmutableMultiDict with the form data username = request.form.get('username') # If you're expecting multiple values for a key, use getlist interests = request.form.getlist('interests') # Process the information # ... return f'Hello, {username}. Your interests: {interests}' if __name__ == '__main__': app.run(debug=True) 

In the above route, submit, request.form is an ImmutableMultiDict that contains the data from a submitted form. We get the username with get and a list of interests with getlist.

Remember to import the request object from the flask module when using it.


More Tags

formidable vlc nsdatecomponents bag r-factor database-restore e-commerce nsdate primes kettle

More Programming Guides

Other Guides

More Programming Examples