Flask 简明教程

Flask – Message Flashing

一个好的基于 GUI 的应用程序会向用户提供有关交互的反馈。例如,桌面应用程序会使用对话框或消息框,而 JavaScript 会使用警报以实现类似目的。

A good GUI based application provides feedback to a user about the interaction. For example, the desktop applications use dialog or message box and JavaScript uses alerts for similar purpose.

在 Flask Web 应用程序中,生成此类信息消息十分容易。Flask 框架的 Flashing 系统能够在一个视图中创建消息,并在名为 next 的视图函数中渲染它。

Generating such informative messages is easy in Flask web application. Flashing system of Flask framework makes it possible to create a message in one view and render it in a view function called next.

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

A Flask module contains flash() method. It passes a message to the next request, which generally is a template.

flash(message, category)

在此,

Here,

  1. message parameter is the actual message to be flashed.

  2. category parameter is optional. It can be either ‘error’, ‘info’ or ‘warning’.

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

In order to remove message from session, template calls get_flashed_messages().

get_flashed_messages(with_categories, category_filter)

这两个参数都是可选的。第一个参数是元组,如果接收到消息,则说明类型。第二个参数对仅显示特定消息很有用。

Both parameters are optional. The first parameter is a tuple if received messages are having category. The second parameter is useful to display only specific messages.

以下闪光灯收到了模板中的消息。

The following flashes received messages in a template.

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

我们现在来看一个简单的例子,演示 Flask 中闪烁机制的操作。在下面的代码中,一个 ‘/’ URL 显示指向登录页面的链接,没有要显示的消息。

Let us now see a simple example, demonstrating the flashing mechanism in Flask. In the following code, a ‘/’ URL displays link to the login page, with no message to flash.

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

这个链接将引导用户到 ‘/login’ URL,后者显示登录表单。提交后, login() 视图函数会验证用户名和密码,然后相应地闪烁 ‘success’ 消息或创建 ‘error’ 变量。

The link leads a user to ‘/login’ URL which displays a login form. When submitted, the login() view function verifies a username and password and accordingly flashes a ‘success’ message or creates ‘error’ variable.

@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)

error 的情况下,重新显示登录模板并附有错误消息。

In case of error, the login template is redisplayed with error message.

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>

另一方面,如果 login 成功,将在索引模板上闪烁一条成功消息。

On the other hand, if login is successful, a success message is flashed on the index template.

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 消息闪烁示例代码如下 −

A complete code for Flask message flashing example is given below −

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)

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

After executing the above codes, you will see the screen as shown below.

flask message flashing example

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

When you click on the link, you will be directed to the Login page.

输入用户名和密码。

Enter the Username and password.

login page

单击 Login 。一条消息“您已成功登录”将被显示。

Click Login. A message will be displayed “You were successfully logged in” .

successfully logged in page