🎓 A1Learner
🔍
0 of 50 lessons completed

Flask Flash Messages

A flash message shows once on the next page. The flash call stores the message, and the next view shows it.

Make the app

This line imports the flash tools together. The secret key lets Flask sign the message.

from flask import Flask, flash, get_flashed_messages, redirect, url_for, render_template_string

app = Flask(__name__)
app.secret_key = "dev-key"

Flash, then redirect

This route stores the message Saved! and redirects to the show page.

@app.route("/save")
def save():
    flash("Saved!")
    return redirect(url_for("show"))

Show the messages

This route reads the stored messages and renders one line per message.

@app.route("/show")
def show():
    messages = get_flashed_messages()
    return render_template_string("{% for m in messages %}<p>{{ m }}</p>{% endfor %}", messages=messages)

Ask twice

The first ask follows the redirect and prints the message. The second ask shows the message is gone.

client = app.test_client()
print(client.get("/save", follow_redirects=True).data.decode())
print(client.get("/show").data.decode() == "")

Example

from flask import Flask, flash, get_flashed_messages, redirect, url_for, render_template_string

app = Flask(__name__)
app.secret_key = "dev-key"

@app.route("/save")
def save():
    flash("Saved!")
    return redirect(url_for("show"))

@app.route("/show")
def show():
    messages = get_flashed_messages()
    return render_template_string("{% for m in messages %}<p>{{ m }}</p>{% endfor %}", messages=messages)

client = app.test_client()
print(client.get("/save", follow_redirects=True).data.decode())
print(client.get("/show").data.decode() == "")

Key points

  • flash("Saved!") stores a message for the next request.
  • get_flashed_messages() reads the stored messages.
  • Flash needs a secret key on the app.
  • Messages show once, then they are gone.

In this example, the /save route flashes "Saved!" and redirects to /show. The /show route reads the stored messages and renders one line per message. The test client follows the redirect and prints the message. A second visit to /show prints True, because the page is now empty and the message is gone.

Note

Flash suits short notes, not long text.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does flash("Saved!") do?