Flask - 闪存消息(Flashing)

Flask - 闪存消息(Flashing) 首页 / Flask入门教程 / Flask - 闪存消息(Flashing)

一个好的基于GUI的应用程序会向用户提供有用的反馈信息。如桌面应用程序使用对话框或消息框,而JavaScript将alert用于类似目的。

在Flask Web应用程序中,生成此类消息很容易, Flask框架自带的刷新系统(Flashing system)能在一个视图中创建消息并在 next 的视图函数中展示该消息。

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

flash(message, category)
  • message 消息信息。

  • category 参数是可选的。可以是"error","info"或"warning"。

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

链接:https://www.learnfk.comhttps://www.learnfk.com/flask/flask-message-flashing.html

来源:LearnFk无涯教程网

get_flashed_messages(with_categories, category_filter)

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

以下内容以模板形式刷新收到的消息。

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

现在让无涯教程看一个简单的示例,演示Flask中的flashing机制。在下面的代码中,‘/' URL显示到登录页面的链接,没有flash的消息。

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

该链接将用户引导至" /login" URL,该URL显示登录表单。提交后login()函数将验证用户名和密码,并将flash"sucess" 消息或创建"error" 变量。

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

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

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 示例的完整代码-

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 Message Flashing Example

当您单击链接时,将定向到"login"页面,输入用户名和密码。

Login Page

点击登录。将显示一条消息"You were successfully logged in"。

Successfully Logged in Page

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

代码精进之路 -〔范学雷〕

从0打造音视频直播系统 -〔李超〕

苏杰的产品创新课 -〔苏杰〕

数据中台实战课 -〔郭忆〕

Linux内核技术实战课 -〔邵亚方〕

Python自动化办公实战课 -〔尹会生〕

说透5G -〔杨四昌〕

业务开发算法50讲 -〔黄清昊〕

Vue 3 企业级项目实战课 -〔杨文坚〕

好记忆不如烂笔头。留下您的足迹吧 :)