What Are Flash Messages?
Flash messages are short-lived notifications, such as 'Your profile was updated' or 'Invalid password', that a view function queues up before redirecting the browser, and which are displayed exactly once on the next page the user sees before being discarded. This solves a common problem in the Post/Redirect/Get pattern: after a form submission triggers a redirect() to avoid duplicate submissions on page refresh, the original view function has already finished and can't directly pass a message to the next request's template — flashing stores the message in the user's session so it survives across that redirect.
Cricket analogy: Like a stadium's electronic scoreboard flashing 'WICKET!' for a few seconds after a dismissal and then reverting to the normal score display, a flashed message appears once on the next page load and then disappears.
Using flash() and get_flashed_messages()
In a view function, calling flash('Profile updated successfully!') stores the message string in session['_flashes'] (a list, so multiple calls to flash() before a single redirect accumulate multiple messages) and requires SECRET_KEY to be configured because Flask's session is a signed cookie. On the receiving template — typically the base layout so it works after any redirect — {% with messages = get_flashed_messages() %}{% if messages %}...{% endif %}{% endwith %} retrieves and simultaneously removes the queued messages from the session, meaning calling it a second time on the same request returns an empty list. This retrieve-and-clear behavior is why flash messages should be pulled exactly once per request, usually in the base template that every page extends.
Cricket analogy: Like a player's review request in DRS being usable only once per dismissal and then consumed regardless of outcome, get_flashed_messages() retrieves and clears the queue in one operation, so calling it twice yields an empty second result.
from flask import Flask, flash, redirect, url_for, render_template
app = Flask(__name__)
app.secret_key = 'change-this-in-production'
@app.route('/profile/update', methods=['POST'])
def update_profile():
success = save_profile_changes()
if success:
flash('Your profile was updated successfully!', 'success')
else:
flash('Something went wrong. Please try again.', 'error')
return redirect(url_for('profile'))
@app.route('/profile')
def profile():
return render_template('profile.html')
Message Categories
flash() accepts an optional second argument, the category, defaulting to 'message' if omitted — common conventions use 'success', 'error', 'warning', and 'info' to let the template apply different Bootstrap or CSS classes per message type. Calling get_flashed_messages(with_categories=True) returns a list of (category, message) tuples instead of plain strings, and get_flashed_messages(category_filter=['error']) can retrieve only messages of specific categories, which is useful if a page needs to render error messages inline near a form while showing success messages as a banner elsewhere on the same page.
Cricket analogy: Like a scorecard color-coding a dismissal in red versus a milestone in gold, flash message categories such as 'error' and 'success' let a template style each notification differently based on its type.
You can call flash() multiple times before a single redirect, and they'll all queue up and render together — useful for listing several validation issues at once, e.g. looping through form.errors and flashing each one with category 'error'.
Displaying Flashes in Templates
The typical pattern renders flashed messages once in base.html so every page inherits the display logic without repeating it: loop over get_flashed_messages(with_categories=True), and for each (category, message) pair render a styled alert <div>, commonly mapping the category to a Bootstrap class like alert-{{ category if category != 'message' else 'info' }}. Because get_flashed_messages() reads from the session, it works correctly regardless of which view rendered the current page — a message flashed in one view and consumed after a redirect() to an entirely different route still displays correctly, which is exactly the cross-request behavior that makes flash messages useful for the Post/Redirect/Get pattern.
Cricket analogy: Like a shared stadium PA system that announces news regardless of which end of the ground the action happened at, placing the flash-rendering loop in base.html means any route's message displays correctly after a redirect to any other route.
Forgetting SECRET_KEY configuration will cause flash() to raise a RuntimeError, since Flask's session (where flashed messages are stored) is a cryptographically signed cookie and cannot be written without a secret key set on the app.
- Flash messages are one-time notifications queued with flash() and displayed on the next request via get_flashed_messages().
- They solve the Post/Redirect/Get problem of passing a message across a redirect, using the session for storage.
- get_flashed_messages() both retrieves and clears the message queue, so it should be called exactly once per request.
- flash() accepts an optional category argument (e.g. 'success', 'error') for conditional styling in templates.
- get_flashed_messages(with_categories=True) returns (category, message) tuples; category_filter can select specific types.
- Rendering the flash loop in base.html ensures messages display correctly regardless of which route redirected to the current page.
- SECRET_KEY must be configured, since flashed messages are stored in Flask's signed session cookie.
Practice what you learned
1. What Flask function queues a one-time notification message before a redirect?
2. What happens when get_flashed_messages() is called a second time within the same request?
3. Where is a flashed message actually stored between the flash() call and its display?
4. What does get_flashed_messages(with_categories=True) return?
5. Why does flash() require SECRET_KEY to be configured on the app?
Was this page helpful?
You May Also Like
Flask Forms with WTForms
Use Flask-WTF and WTForms to define form fields declaratively, validate user input server-side, and protect submissions with CSRF tokens.
Jinja2 Templating
Learn how Flask uses the Jinja2 templating engine to render dynamic HTML by mixing Python-like expressions, control structures, and template inheritance into your views.
Handling File Uploads
Accept, validate, and securely store user-uploaded files in Flask using multipart forms, filename sanitization, and upload size limits.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics
Web DevelopmentNext.js Study Notes
JavaScript · 30 topics