在 Flask 中,消息闪现是一种在一次请求中传递消息给下一次请求的机制。这对于在重定向之后显示一次性通知消息(例如成功消息或错误消息)非常有用。Flask 提供了 flash 和 get_flashed_messages 来实现消息闪现。

以下是一个简单的示例:
from flask import Flask, render_template, redirect, url_for, flash

app = Flask(__name__)
app.secret_key = 'your_secret_key'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login/<username>')
def login(username):
    # 模拟登录过程
    # 在实际应用中,这里可能是检查用户名和密码的地方
    flash('Login successful!', 'success')
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)

在这个例子中,flash 函数用于在一次请求中存储消息。在 /login 路由中,当用户成功登录时,使用 flash('Login successful!', 'success') 存储一个成功消息,类型为 'success'。然后,用户被重定向到主页。

在模板文件 index.html 中,你可以使用 get_flashed_messages 来获取并显示闪现的消息:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Flash Messages</title>
</head>
<body>
    <h1>Welcome to the Flask Flash Messages Example</h1>
    
    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            <ul>
                {% for message, category in messages %}
                    <li class="{{ category }}">{{ message }}</li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endwith %}

    <p><a href="{{ url_for('login', username='John') }}">Login</a></p>
</body>
</html>

在模板中,get_flashed_messages(with_categories=true) 返回一个元组列表,其中包含消息和消息的类型。模板使用这些信息来显示相应的样式(例如,使用 'success' 类型显示成功消息)。

请注意,在实际应用中,你可能会使用更复杂的消息和样式,这个例子只是一个简单的演示。消息闪现是一个很好的方式,可以在多个请求之间传递一次性的通知信息。


转载请注明出处:http://www.zyzy.cn/article/detail/7310/Flask