Flask – Message Flashing

基于GUI的良好应用程序向用户提供有关交互的反馈.例如,桌面应用程序使用对话框或消息框,JavaScript使用警报用于类似目的.

在Flask Web应用程序中生成此类信息性消息很容易. Flask框架的闪烁系统可以在一个视图中创建消息,并在名为 next 的视图函数中呈现它.

Flask模块包含 flash()方法.它将消息传递给下一个请求,通常是一个模板.

flash(message, category)

在这里,

  • 消息参数是实际的消息要闪现.

  • 类别参数是可选的.它可以是'错误','信息'或'警告'.

为了从会话中删除消息,模板调用 get_flashed_messages().

get_flashed_messages(with_categories, category_filter)

这两个参数都是可选的.如果接收的消息具有类别,则第一个参数是元组.第二个参数仅用于显示特定消息.

以下闪烁模板中收到的消息.

{% with messages = get_flashed_messages() %}
   {% if messages %}
      {% for message in messages %}
         {{ message }}
      {% endfor %}
   {% endif %}
{% endwith %}

现在让我们看一个简单的例子,演示闪烁机制在烧瓶中.在以下代码中,'/' URL显示指向登录页面的链接,没有消息要闪存.

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

该链接将用户引导至显示登录表单的'/login' URL.提交后,登录()视图功能会验证用户名和密码,并相应地闪烁'成功'消息或创建'错误'变量.

@app.route('/login', methods = ['GET', 'POST'])
def login():
   error = None
   
   if request.method == 'POST':
      if request.form['username'] != 'admin' or \
         request.form['password'] != 'admin':
         error = 'Invalid username or password. Please try again!'
      else:
         flash('You were successfully logged in')
         return redirect(url_for('index'))
   return render_template('login.html', error = error)

如果错误,将重新显示登录模板并显示错误消息.

Login.html

<!doctype html>
<html>
   <body>
      <h1>Login</h1>

      {% if error %}
         <p><strong>Error:</strong> {{ error }}
      {% endif %}
      
      <form action = "" method = post>
         <dl>
            <dt>Username:</dt>
            <dd>
               <input type = text name = username 
                  value = "{{request.form.username }}">
            </dd>
            <dt>Password:</dt>
            <dd><input type = password name = password></dd>
         </dl>
         <p><input type = submit value = Login></p>
      </form>
   </body>
</html>

另一方面,如果登录成功,则会在索引模板上闪烁成功消息.

Index.html

<!doctype html>
<html>
   <head>
      <title>Flask Message flashing</title>
   </head>
   <body>
      {% with messages = get_flashed_messages() %}
         {% if messages %}
            <ul>
               {% for message in messages %}
               <li<{{ message }}</li>
               {% endfor %}
            </ul>
         {% endif %}
      {% endwith %}
		
      <h1>Flask Message Flashing Example</h1>
      <p>Do you want to <a href = "{{ url_for('login') }}">
         <b>log in?</b></a></p>
   </body>
</html>

Flask信息闪烁示例的完整代码在下面给出 :

Flash.py

from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.secret_key = 'random string'

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

@app.route('/login', methods = ['GET', 'POST'])
def login():
   error = None
   
   if request.method == 'POST':
      if request.form['username'] != 'admin' or \
         request.form['password'] != 'admin':
         error = 'Invalid username or password. Please try again!'
      else:
         flash('You were successfully logged in')
         return redirect(url_for('index'))
			
   return render_template('login.html', error = error)

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

执行上述代码后,您将看到如下所示的屏幕.

Flask消息闪烁示例

当您单击该链接时,您将被定向到登录页面.

输入用户名和密码.

登录页面

单击登录.将显示一条消息"您已成功登录".

Successfully Logged in Page