Message flashing in Flask explained and why are they important?

In this tutorial, we are going to learn about message flashing in Flask. We are also going to learn why are they essential in any webpage and how to implement them in our Flask webpage.

Flask – Message Flashing

When we use a proper GUI application, it provides us with feedback for good interaction. We can also take that by an example, as JavaScript uses alert and desktop applications use dialog box and a message box.

But you might think that implementing such kind of a feature into our webpage is a difficult task, but let me tell you that generating such a variety of messages is quite easy in a Flask web application. There is a Flashing system in the Flask framework of Python, which makes it easy and possible to create messages in one view and display them in a view function known as next.

For implementing message flashing, Flask module contains a flash() function, which passes on the message to the next request, which is generally a template.

flash(message, category)

In the above syntax of the flash() function has the following two parameters –

  • Message parameter which defines the message to be passed on and is a mandatory parameter.
  • Category parameter which is an optional parameter. It includes categories such as ‘info,’ ‘error,’ and ‘warning.’

In the above flash() function, it is mandatory to pass a message. But there is an option to remove messages from the session, and for that purpose, the template calls the get_flashed_messages() function.

get_flashed_messages(with_categories, category_filter)

In this, both the parameters are optional. They are –

  • with_categories parameter is a tuple if the messages received have a category.
  • category_filter parameter is used to display some specific messages.

The following piece of code flashes messages in a template –

{% with messages = get_flashed_messages() %}
   {% if messages %}
      {% for message in messages %}
         {{ message }}
      {% endfor %}
   {% endif %}
{% endwith %}

 

Now let us explain the same thing with the help of an example. In the following piece of code, the flashing process in Flask is explained. Here, the ‘/‘ URL is used to display a link to the login page, but without a message to flash.

@app.route('/')
def index():
   return render_template('index.html')

That link leads a user to the ‘/login‘ URL which then displays the login form.

@app.route('/login', methods = ['GET', 'POST'])
def login():
   error = None
   
   if request.method == 'POST':
      if request.form['username'] != 'admin' or \
         request.form['password'] != 'admin':
         error = 'Invalid username or password. Please try again!'
      else:
         flash('You were successfully logged in')
         return redirect(url_for('index'))
   return render_template('login.html', error = error)

On submitting the login form, the login() view function checks for a username and a password. Then accordingly it flashes the ‘success‘ message or creates an ‘error‘ variable. In case of ‘error‘, the login template is then displayed.

Login.html

<!doctype html>
<html>
   <body>
      <h1>Login</h1>

      {% if error %}
         <p><strong>Error:</strong> {{ error }}
      {% endif %}
      
      <form action = "" method = post>
         <dl>
            <dt>Username:</dt>
            <dd>
               <input type = text name = username 
                  value = "{{request.form.username }}">
            </dd>
            <dt>Password:</dt>
            <dd><input type = password name = password></dd>
         </dl>
         <p><input type = submit value = Login></p>
      </form>
   </body>
</html>

And here you go with all of message flashing in Flask.

 

I hope you understood what was explained in this tutorial. If you have any doubts or queries regarding anything described here, please feel free to comment them down below.

Leave a Reply

Your email address will not be published. Required fields are marked *