Flask - Message Flashing
Flask – Message Flashing
Section titled “Flask – Message Flashing”Good user interfaces provide feedback. After a user performs an action (like submitting a form, logging in, or deleting an item), it’s helpful to display a short, temporary message confirming the action or indicating success/failure. This is often called “message flashing”.
Flask’s flashing system provides a convenient way to record a message at the end of one request and access it in the next request (and only the next request). This is ideal for displaying status messages after redirects.
How it Works
Section titled “How it Works”- Flashing: In a view function, call
flash('Your message', 'category'). This stores the message (and optional category) in the user’s session. - Redirecting (Optional but Common): Often, after flashing a message, you’ll redirect the user to another page using
redirect(url_for(...)). - Retrieving: In the view function or template for the next request, call
get_flashed_messages()to retrieve the stored messages. - Displaying: Render the retrieved messages in your template. Once retrieved, messages are removed from the session.
- Requires Secret Key: Since flashing uses the session,
app.secret_keymust be configured.
The flash() Function
Section titled “The flash() Function”from flask import flash
# Flash a simple messageflash('Login successful!')
# Flash a message with a category for stylingflash('Invalid password.', 'error')flash('Settings saved.', 'success')Parameters:
message: The string containing the message to display.category(optional): A string used to classify the message (e.g., ‘success’, ‘error’, ‘info’, ‘warning’). This is useful for applying different CSS styles.
The get_flashed_messages() Function
Section titled “The get_flashed_messages() Function”This function is typically called within a template (often a base layout template) to retrieve and display messages.
{# Example in Jinja2 template #}
{# Method 1: Get messages without categories #}{% with messages = get_flashed_messages() %} {% if messages %} <div class="alert-messages"> <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> </div> {% endif %}{% endwith %}
{# Method 2: Get messages with categories for styling #}{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} <div class="alert-messages"> {% for category, message in messages %} <div class="alert alert-{{ category }}">{{ message }}</div> {% endfor %} </div> {% endif %}{% endwith %}Parameters:
with_categories=False(default): Returns a list of message strings.with_categories=True: Returns a list of(category, message)tuples.category_filter=[]: An iterable of categories to filter for. Only messages matching these categories will be returned (requireswith_categories=True).
Example: Login Feedback with Flashing
This example shows a login form that flashes success or error messages.
- Create
templates/layout_flash.html(Base Template):
<!doctype html><html> <head> <title>Flask Flashing Example</title> <style> .alert { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; } .alert-success { color: #3c763d; background-color: #dff0d8; border-color: #d6e9c6; } .alert-error { color: #a94442; background-color: #f2dede; border-color: #ebccd1; } .alert-messages { list-style: none; padding: 0; } </style> </head> <body> <h1>Flask Flashing Example</h1>
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} <ul class="alert-messages"> {% for category, message in messages %} <li class="alert alert-{{ category|default('info') }}">{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %}
{% block body %}{% endblock %} </body></html>- Create
templates/index_flash_example.html(Home Page):
{% extends 'layout_flash.html' %}{% block body %} <p>Welcome! Please <a href="{{ url_for('login_page') }}">log in</a>.</p>{% endblock %}- Create
templates/login_flash_example.html(Login Page):
{% extends 'layout_flash.html' %}{% block body %} <h2>Login</h2> <form action="{{ url_for('do_login') }}" method=post> <dl> <dt>Username:</dt> <dd><input type=text name=username></dd> <dt>Password:</dt> <dd><input type=password name=password></dd> </dl> <p><input type=submit value=Login></p> </form>{% endblock %}- Create the Flask Application (
app.py):
from flask import Flask, flash, redirect, render_template, request, url_forimport os
app = Flask(__name__)# IMPORTANT: Use a secure, random secret key, ideally from env varsapp.secret_key = os.environ.get('SECRET_KEY', b'_5#y2L"F4Q8z\n\xec]/')
@app.route('/flash-example/')def index(): return render_template('index_flash_example.html')
@app.route('/flash-example/login')def login_page(): return render_template('login_flash_example.html')
@app.route('/flash-example/do-login', methods=['POST'])def do_login(): # Simulate checking credentials if request.form['username'] == 'admin' and request.form['password'] == 'secret': flash('You were successfully logged in!', 'success') # Redirect to index after successful login return redirect(url_for('index')) else: flash('Invalid username or password. Please try again!', 'error') # Redirect back to login page to show error return redirect(url_for('login_page'))
if __name__ == "__main__": app.run(debug=True, port=5007) # Use a different port if neededRun the app, navigate to /flash-example/. Click the login link. Try logging in with incorrect credentials (error message shown on login page). Try logging in with correct credentials (admin/secret) (success message shown on index page).
Message flashing provides simple, effective feedback for users interacting with your web application.