Flask - 消息闪现
Flask – 消息闪现 (Message Flashing)
Section titled “Flask – 消息闪现 (Message Flashing)”良好的用户界面会提供反馈。用户执行某个操作(如提交表单、登录或删除项目)后,显示一条短暂的、临时性的消息来确认该操作或指示成功/失败,这是非常有帮助的。这通常被称为“消息闪现 (Message Flashing)”。
Flask 的消息闪现系统提供了一种便捷的方式,可以在一个请求结束时记录一条消息,并在下一个请求中(且仅在下一个请求中)访问它。这对于在重定向后显示状态消息非常理想。
- 闪现消息: 在一个视图函数 (view function) 中,调用
flash('你的消息', '类别')。这会将消息(和可选的类别)存储到用户的会话 (session) 中。 - 重定向 (可选但常用): 通常,在闪现消息后,您会使用
redirect(url_for(...))将用户重定向到另一个页面。 - 获取消息: 在下一个请求 (request) 的视图函数或模板 (template) 中,调用
get_flashed_messages()来获取存储的消息。 - 显示消息: 在模板中渲染 (render) 获取到的消息。消息一旦获取,就会从会话中移除。
- 需要密钥: 由于消息闪现使用了会话 (session),因此必须配置
app.secret_key。
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')参数:
message: 要显示的消息字符串。category(可选): 用于对消息进行分类的字符串(例如,‘success’、‘error’、‘info’、‘warning’)。这对于应用不同的 CSS 样式很有用。
The get_flashed_messages() Function
Section titled “The get_flashed_messages() Function”此函数通常在模板 (template) 中调用(通常在基础布局模板中),用于获取和显示消息。
{# Jinja2 模板中的示例 #}
{# 方法 1: 获取不带类别的消息 #}{% with messages = get_flashed_messages() %} {% if messages %} <div class="alert-messages"> <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> </div> {% endif %}{% endwith %}
{# 方法 2: 获取带类别的消息以应用样式 #}{% 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 %}参数:
with_categories=False(默认值): 返回一个消息字符串列表。with_categories=True: 返回一个(类别, 消息)元组列表。category_filter=[]: 一个可迭代对象,用于过滤类别。仅返回匹配这些类别的消息(需要with_categories=True)。
示例: 使用消息闪现实现登录反馈
本示例展示了一个登录表单,它会闪现成功或错误消息。
- 创建
templates/layout_flash.html(基础模板):
<!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>- 创建
templates/index_flash_example.html(首页):
{% extends 'layout_flash.html' %}{% block body %} <p>Welcome! Please <a href="{{ url_for('login_page') }}">log in</a>.</p>{% endblock %}- 创建
templates/login_flash_example.html(登录页):
{% 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 %}- 创建 Flask 应用 (
app.py):
from flask import Flask, flash, redirect, render_template, request, url_forimport os
app = Flask(__name__)# 重要提示: 使用一个安全的、随机的密钥,最好来自环境变量app.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(): # 模拟检查凭据 if request.form['username'] == 'admin' and request.form['password'] == 'secret': flash('You were successfully logged in!', 'success') # 登录成功后重定向到首页 return redirect(url_for('index')) else: flash('Invalid username or password. Please try again!', 'error') # 失败后重定向回登录页显示错误 return redirect(url_for('login_page'))
if __name__ == "__main__": app.run(debug=True, port=5007) # 如果需要,请使用不同的端口运行应用,导航到 /flash-example/。点击登录链接。尝试使用错误凭据登录(登录页显示 error 消息)。尝试使用正确凭据登录(admin/secret)(首页显示 success 消息)。
消息闪现为用户与您的 Web 应用交互提供了简单有效的反馈。