Python Flask – ImmutableMultiDict
MultiDict is a sub-class of Dictionary that can contain multiple values for the same key, unlike normal Dictionaries. It is used because some form elements have multiple values for the same key and it saves the multiple values of a key in form of a list.
Example:
Python3
from werkzeug.datastructures import MultiDict orders = MultiDict([( 1 , 'GFG' ), ( 1 , 'Geeks' )]) print (orders[ 1 ]) print (orders.getlist( 1 )) |
Output:
GFG ['GFG', 'Geeks']
In this article, we will see how to get MultiDict data from the form in Flask.
Let us write a simple HTML page with a form tag and submit it to a flask route. The request.form object which is used to get the contents from the form during POST request is of type ImmutableMultiDict.
Index.HTML
HTML
<!DOCTYPE html> < html > < head > < title >Input Page</ title > </ head > < body > < form method = 'POST' action = "save" > < input type = "text" name = "username" id = "uname" /> < input type = "submit" value = "Submit" /> </ form > </ body > </ html > |
Let us write another HML file that will shoe the type of the data given by the POST request.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title >Home</ title > </ head > < body > {{userInput}} </ body > </ html > |
Creating Flask app
We will create a simple flask app that will render the above-created form at the URL http://127.0.0.1:5000/input and will show the data submitted using the POST request at the URL http://127.0.0.1:5000/save
Python3
from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) @app .route( '/input' , methods = [ 'GET' ]) def input (): return render_template( 'index.html' ) @app .route( '/save' , methods = [ 'POST' ]) def save(): userInput = request.form return render_template( 'home.html' , userInput = userInput) if __name__ = = '__main__' : app.run() |
Output:
Please Login to comment...