Flask Flashing
In the web applications, there are scenarios where the developer might need to flash the messages to provide feedback to the users for the behavior of the application in different cases.
Flask provides the flash() method, in the same way, the client-side scripting language like JavaScript uses the alerts or the python GUI framework Tkinter uses the dialogue box or the message box.
The flash() method is used to generate informative messages in the flask. It creates a message in one view and renders it to a template view function called next.
In other words, the flash() method of the flask module passes the message to the next request which is an HTML template. The syntax to use the flash() method is given below.
It accepts the following parameters.
- message: it is the message to be flashed to the user.
- Category: It is an optional parameter. Which may represent any error, information, or warning.
The messages are generated in the flask script using the flash() method of flask module. These messages need to be extracted in the template from the session. For this purpose, the method get_flashed_messages() is called in the HTML template.
The syntax to use this method is given below.
It accepts the following parameters.
- with_categories: This parameter is optional and used if the messages have the category.
- category_filter: This parameter is also optional. It is useful to display only the specified messages.
Example
The example contains the flask and HTML scripts for server and client-side scripting.
The python script flashes the messages and redirects the user to the different HTML script depending upon the successful and unsuccessful login of the user.
flashing.py
index.html
login.html
The URL /index shows the following template (index.html) which contains the code for flashing the message (if any). The link login redirects the user to the URL /login.
The following page shows the template login.html which prompts the user to enter the email id and password. Here, if the user enters any random password other than “jtp“, it can not be able to login to the application.
The following URL illustrates the first case where the user has entered the wrong password. The script login.py generates an error message as “invalid password” and redirects the user to this page itself.
The following URL illustrates the second case where the user has entered the correct password as “jtp” and therefore the script flashing.py flashes the success message and redirect the user to the URL http:localhost:5000/index.