Mensajes flash in Flask

- Andrés Cruz

En español
Mensajes flash in Flask

Showing confirmation messages according to the operation performed is a regular task; in many other technologies including Flash, there are flash messages, which are those that only last one on request, therefore, they are ideal to indicate whether the record is created, updated or deleted correctly or simply a system error or other message; for this, we have the function called flash() that receives as an argument the corresponding message:

my_app\tasks\controllers.py

from flask import flash
***
@taskRoute.route('/update/<int:id>', methods=['GET','POST'])
def update(id:int):
   ***
   if form.validate_on_submit():
      operations.update(form.name.data, form.category.data)
      flash('The registry has been updated successfully')
   return render_template('dashboard/task/update.html', form=form, formTag=formTag, formTagDelete=forms.TaskTagRemove() ,task=task, id=id)

Now, to display the message, we do it from the templates using the get_flashed_messages() function that returns a list of the established messages (we can establish more than one message per request) and we iterate them:

my_app\templates\dashboard\master.html

***
<body>
    {% with messages = get_flashed_messages() %}
    {% if messages %}
    <ul class=flashes>
        {% for message in messages %}
        <li>{{ message }}</li>
        {% endfor %}
    </ul>
    {% endif %}
    {% endwith %}
***

Since flash messages can be used in any situation and not only in the previous CRUD operations, it is a good idea to place them in the template, so that once established from the controller, they can be displayed without importing the controller that defines them.

Categories

It is also possible to define categories in the messages, this is useful if depending on the type of message you want to place a different design, for example, if the message is informative, we place a blue container:

Messagje error
Messagje information

Or if it is an error, a red color:

Messagje error

Among other possible adaptations; to do this, we define a second parameter to the flash() function that corresponds to the category:

flash('The registry has been updated successfully', 'info')

And from the template, we can filter by category:

{% with infos = get_flashed_messages(category_filter=["info"]) %}
{% if errors %}
    {%- for msg in infos %}
***

Or we can indicate that when obtaining the list of flash messages, return the category in a tuple:

{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
   {% for message in messages %}
***

And we will have the category as part of the message:

('info', 'The registry has been updated successfully')
Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.