flask
  1. flask-flashing

Flashing - Error Handling and Redirects in Flask

Syntax

flash(message, category='message')

Example

from flask import Flask, redirect, url_for, request, flash, render_template

app = Flask(__name__)
app.secret_key = 'some_secret'

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

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if username == 'admin' and password == 'admin':
            flash('Logged in successfully!', 'success')
            return redirect(url_for('home'))
        else:
            flash('Login unsuccessful. Please check your credentials!', 'danger')
    return render_template('login.html')

if __name__ == '__main__':
    app.run()

Output

The output of this example will depend on the templates used. In general, the flash() function will send a message to the next request and it can be displayed in a template using the get_flashed_messages() function.

Explanation

Flashing is a technique used in Flask to provide feedback to the user. It allows you to send messages from one request to the next and is typically used to display error or success messages after a form submission.

The flash() function is used to add a message to the session. The first argument is the message string and the second argument, if provided, is the category of the message. This can be used to style the message differently depending on its type, such as success, danger, warning, info, etc.

The get_flashed_messages() function can be used in the template to retrieve the flashed messages from the previous request and display them.

Use

Flashing can be useful in a number of scenarios, including:

  • Displaying error messages to the user after a form submission
  • Displaying success messages to the user after completing an action
  • Providing feedback to the user during a long-running process (e.g. "Please wait while we process your request")

Important Points

  • The flash() function is session-based, so the messages will only persist for one request/response cycle.
  • The get_flashed_messages() function returns a list of message tuples. Each tuple contains the message string and the message category.
  • Flask provides a number of built-in views that use flashing, such as the abort() function, which displays an error message and redirects the user to the error page.

Summary

Flashing is a technique used in Flask to provide feedback to the user. It allows you to send messages from one request to the next and is typically used to display error or success messages after a form submission. The flash() function is used to add a message to the session and the get_flashed_messages() function can be used in the template to retrieve the flashed messages from the previous request and display them.

Published on: