Categories
Flask

Python Web Development with Flask — Flash Messages

Spread the love

Flask is a simple web framework written in Python.

In this article, we’ll look at how to develop simple Python web apps with Flask.

Message Flashing

We can send messages to a template that can be accessed with the next request.

For example, we can write:

app.py

from flask import Flask, render_template, redirect, url_for, flash, request
app = Flask(__name__)
app.secret_key = b'secret'

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

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        flash('You were successfully logged in')
        return redirect(url_for('index'))
    return render_template('login.html', error=error)

templates/login.html

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

templates/layout.html

<!doctype html>
<title>My Application</title>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
  {% for message in messages %}
  <li>{{ message }}</li>
  {% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}{% endblock %}

templates/index.html

{% extends "layout.html" %}
{% block body %}
  <h1>Overview</h1>
  <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>
{% endblock %}

We create the flash message with the flash function in app.py .

Then when login is successful, we should the message in the template with the get_flashed_messages function.

Flashing With Categories

We can call flash with a second argument.

The 2nd argument is the category name.

To add the category and render it, we can write:

app.py

from flask import Flask, render_template, redirect, url_for, flash, request
app = Flask(__name__)
app.secret_key = b'secret'

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

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        flash('You were successfully logged in', 'info')
        return redirect(url_for('index'))
    return render_template('login.html', error=error)

templates/login.html

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

templates/layout.html

<!doctype html>
<title>My Application</title>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul class=flashes>
  {% for category, message in messages %}
  <li class="{{ category }}">{{ message }}</li>
  {% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}{% endblock %}

templates/index.html

{% extends "layout.html" %}
{% block body %}
  <h1>Overview</h1>
  <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>
{% endblock %}

In app.py , we have:

flash('You were successfully logged in', 'info')

to add the 'info' category.

The in layout.html . we call get_flashed_messages with the with_categories parameter set to true to render the category.

Then in the for loop, we get both the category and message and render them.

Filtering Flash Messages

We can also filter flash messages in the template.

For example in templates/layout.html , we write:

<!doctype html>
<title>My Application</title>
{% with messages = get_flashed_messages(category_filter=["info"]) %}
{% if messages %}
<ul class=flashes>
  {% for message in messages %}
  <li>{{ message }}</li>
  {% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}{% endblock %}

to add the category_filter argument to only display flash messages with category 'info' .

Conclusion

We can add flash messages that are displayed in the next request into our templates.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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