Flash messages show quick notes to users after actions, like "Success" or "Error". They help users know what happened.
Flash messages for user feedback in Flask
from flask import flash flash('Your message here', 'category')
The flash() function stores a message for the next page load.
The optional category helps style messages differently, like 'error' or 'success'.
flash('Login successful', 'success')
flash('Invalid password', 'error')
flash('Welcome back!')This Flask app shows a form to enter a username. When submitted, it flashes a success message if a username is entered or an error if empty. The messages appear on the page with colors.
from flask import Flask, render_template_string, request, redirect, url_for, flash, get_flashed_messages app = Flask(__name__) app.secret_key = 'secret123' # Needed for flashing messages @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': username = request.form.get('username', '') if username: flash(f'Welcome, {username}!', 'success') return redirect(url_for('index')) else: flash('Please enter a username.', 'error') return redirect(url_for('index')) messages = get_flashed_messages(with_categories=True) return render_template_string(''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flash Messages Demo</title> <style> body { font-family: Arial, sans-serif; padding: 2rem; } .flash { padding: 1rem; margin-bottom: 1rem; border-radius: 0.5rem; } .success { background-color: #d4edda; color: #155724; } .error { background-color: #f8d7da; color: #721c24; } </style> </head> <body> <h1>Enter your username</h1> <form method="POST"> <input type="text" name="username" aria-label="Username" required> <button type="submit">Submit</button> </form> {% for category, message in messages %} <div class="flash {{ category }}" role="alert">{{ message }}</div> {% endfor %} </body> </html> ''', messages=messages) if __name__ == '__main__': app.run(debug=True)
Always set app.secret_key to enable flashing.
Use get_flashed_messages(with_categories=True) to get messages with their categories for styling.
Flash messages last only for the next request, so they disappear after showing once.
Flash messages give quick feedback to users after actions.
Use flash() to store messages and display them in templates.
Categories help style messages differently, like success or error.
Practice
flash() in a Flask application?Solution
Step 1: Understand the role of flash messages
Flash messages are temporary messages shown to users after actions like form submission.Step 2: Identify what
Theflash()doesflash()function stores these messages to be displayed once, then removed.Final Answer:
To send a one-time message to the user after a request -> Option CQuick Check:
Flash messages = one-time user feedback [OK]
- Thinking flash stores data permanently
- Confusing flash with routing or database functions
- Assuming flash messages appear multiple times
flash in a Flask app?Solution
Step 1: Recall correct import syntax in Flask
Functions likeflashare imported directly from theflaskpackage usingfrom flask import flash.Step 2: Check usage after import
After importing, callingflash('Message')is the correct way to flash a message.Final Answer:
from flask import flash; flash('Message') -> Option AQuick Check:
Correct import and call = from flask import flash; flash('Message') [OK]
- Using incorrect import syntax
- Trying to import flash as a submodule
- Calling flash without importing
from flask import Flask, flash, render_template_string, get_flashed_messages
app = Flask(__name__)
app.secret_key = 'secret'
@app.route('/')
def index():
flash('Welcome back!', 'info')
messages = get_flashed_messages(with_categories=True)
return render_template_string('''
{% for category, message in messages %}
<div class="{{ category }}">{{ message }}</div>
{% endfor %}
''', messages=messages)Solution
Step 1: Understand flash message with category
The code flashes a message 'Welcome back!' with category 'info'. Usingget_flashed_messages(with_categories=True)returns a list of (category, message) tuples.Step 2: Analyze template rendering
The template loops over messages and creates a div with class set to the category and content as the message. So it outputs <div class="info">Welcome back!</div>.Final Answer:
<div class="info">Welcome back!</div> -> Option DQuick Check:
Flash with category 'info' outputs div with class 'info' [OK]
- Ignoring categories and using wrong class name
- Assuming flash messages are empty immediately
- Misreading template syntax causing syntax error
from flask import Flask, flash
app = Flask(__name__)
@app.route('/')
def index():
flash('Hello user!')
return 'Done'Solution
Step 1: Recall flash message requirements
Flashing messages requires session support, which needsapp.secret_keyto be set.Step 2: Identify missing secret key
The code does not setapp.secret_key, so flashing will not work properly and may raise an error.Final Answer:
Missing app.secret_key causes flash to fail -> Option BQuick Check:
Secret key needed for flash session [OK]
- Forgetting to set secret_key
- Thinking flash needs category argument
- Believing flash must be returned
Solution
Step 1: Flash messages with categories
Useflash('message', 'category')-- category as the second positional argument.Step 2: Retrieve messages with categories in template
Loop overget_flashed_messages(with_categories=True)directly in the template to unpack (category, message) and applyclass="{{ category }}"for distinct styles.Step 3: Distractors fail because
No categories provided; invalid keyword argument liketype='success'raises TypeError; retrieving withoutwith_categories=Truereturns strings causing unpack error infor category, msg in messages.Final Answer:
flash('Form submitted!', 'success'); flash('Invalid input', 'error'); template with get_flashed_messages(with_categories=True) -> Option AQuick Check:
Flash with categories + template loop with categories = flash('Form submitted!', 'success')\nflash('Invalid input', 'error')\nreturn render_template('index.html')\n \n{% for category, msg in get_flashed_messages(with_categories=True) %}\n{{ msg }}
\n{% endfor %} [OK]
- Not passing with_categories=True when retrieving messages
- Using invalid keyword argument like type= for category
- Passing messages without categories to template expecting categories
Ready to prove it?
Pass the test and this pattern moves unknown
