Introduction
Flask provides a convenient way to give user feedback through message flashing. Message flashing allows you to display temporary messages to users, such as success messages, error notifications, and informational alerts. In this guide, we'll explore how to use Flask's message flashing for user feedback.
Step 1: Flashing Messages in Flask
Flask provides the `flash` function to add messages to the message flashing system. Here's an example:
from flask import Flask, flash, redirect, render_template, url_for
app = Flask(__name)
app.secret_key = 'your_secret_key'
@app.route('/success')
def success():
flash('Success! Your action was completed.')
return redirect(url_for('show_messages'))
@app.route('/error')
def error():
flash('Error! An error occurred while processing your request.')
return redirect(url_for('show_messages'))
@app.route('/show_messages')
def show_messages():
return render_template('messages.html')
if __name__ == '__main__':
app.run()
In this example, when a user accesses the `/success` or `/error` routes, a message is flashed, and they are redirected to the `/show_messages` route, which displays the messages.
Step 2: Displaying Flashed Messages
To display flashed messages in your HTML templates, you can use the `get_flashed_messages` function. Here's an example of how to display flashed messages in a template named "messages.html":
<!DOCTYPE html>
<html>
<head>
<title>Message Flashing Example</title>
</head>
<body>
<h1>Flashed Messages</h1>
<ul>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
{% else %}
<li>No messages to display</li>
{% endif %}
{% endwith %}
</ul>
</body>
</html>
Conclusion
Flask message flashing is a valuable tool for providing user feedback in web applications. By following these steps, you can flash messages, display them to users, and create a more interactive and informative user experience. Message flashing is particularly useful for success messages, error notifications, and other temporary alerts.