Flash Messages
Flash messages are one-time messages stored in the user’s session.
They’re commonly used after:
- successful form submission
- login/logout
- errors like “invalid password”
flowchart LR
A["POST /subscribe"] --> B["flash('Subscribed!', 'success')"]
B --> C[("session cookie")]
C --> D["redirect to /"]
D --> E["GET /"]
E --> F["get_flashed_messages() in the template"]
F --> G["message rendered"]
F --> H["and removed from the session"]
H --> I["a reload shows nothing -- it was consumed"]
Flashing a message
Section titled “Flashing a message”from flask import flash, redirect, url_for
@app.route("/subscribe", methods=["POST"])
def subscribe():
# ...do work...
flash("Subscribed successfully!", "success")
return redirect(url_for("home"))The second argument ("success") is a category.
Display flash messages in templates
Section titled “Display flash messages in templates”In your base template:
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul>
{% for category, message in messages %}
<li class="flash {{ category }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}Requirements
Section titled “Requirements”Flashing uses sessions, so you need SECRET_KEY configured.
Best practice
Section titled “Best practice”Use flash + redirect (PRG pattern) so the message shows on the GET page.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading