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. It is usually used to get the Information passed in a Form.
Example:
Python3
from werkzeug.datastructures import ImmutableMultiDict data = ImmutableMultiDict([( 'input' , 'GFG' ), ( 'input' , 'Geeks For Geeks' )]) print (data.getlist( 'input' )) |
Output:
['GFG', 'Geeks For Geeks']
Now, Let’s see how to get MultiDict data from the form in Flask. With some simple HTML code to make a form and submit it to a flask route.
After that, the request form object will be used to get the data from the form.
home.html
Make Sure this file is in the ‘templates’ folder
HTML
<!DOCTYPE html> < html > < head > < title >Input Page</ title > </ head > < body > < form method = 'POST' > < label for = "username" >Write Username:</ label > < input type = "text" name = "username" id = "uname" /> < label for = "password" >Write Password:</ label > < input type = "text" name = "password" id = "pword" /> < input type = "submit" value = "Submit" /> </ form > </ body > </ html > |
Now create an app.py
Here, The home function is being used as the handler for the route, It simply renders the home.html file and when a POST at the URL. It simply returns the ‘im_dict’. It is nothing but actually, an ImmutableMultiDict which has all the data contained in the form.
Python3
from flask import Flask, render_template, request app = Flask(__name__) @app .route( '/' , methods = [ 'GET' , 'POST' ]) def home(): if request.method = = 'POST' : im_dict = request.form return (f '<h1>{im_dict}</h1>' ) return render_template( 'home.html' ) if __name__ = = '__main__' : app.run(debug = True ) |
Output:
This shows an ImmutableMultiDict with the keys ‘username’ and ‘password’.