Flash 消息
请求完成后,有时需要让用户知道状态发生了变化。这里可以使用确认消息、警告或者错误提醒。一个典型例子是,用户提交了有一项错误的登录表单后,服务器发回的响应重新渲染了登录表单,并在表单上面显示一个消息,提示用户用户名或密码错误。
这种功能是 Flask
的核心特性。如示例6 所示,flash()
函数可实现这种效果。
示例6 hello.py
:Flash
消息
from flask import Flask, render_template, session, redirect, url_for, flash
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
old_name = session.get('name')
if old_name is not None and old_name != form.name.data:
flash('Looks like you have changed your name!')
session['name'] = form.name.data
return redirect(url_for('index'))
return render_template('index.html',
form = form, name = session.get('name'))
在这个示例中,每次提交的名字都会和存储在用户会话中的名字进行比较,而会话中存储的名字是前一次在这个表单中提交的数据。如果两个名字不一样,就会调用 flash()
函数,在发给客户端的下一个响应中显示一个消息。
仅调用 flash()
函数并不能把消息显示出来,程序使用的模板要渲染这些消息。最好在基模板中渲染 Flash
消息,因为这样所有页面都能使用这些消息。Flask
把 get_flashed_messages()
函数开放给模板,用来获取并渲染消息,如示例7 所示。
示例7 templates/base.html
:渲染 Flash
消息
{% block content %}
<div class="container">
{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ message }}
</div>
{% endfor %}
{% block page_content %}{% endblock %}
</div>
{% endblock %}
在模板中使用循环是因为在之前的请求循环中每次调用 flash()
函数时都会生成一个消息,所以可能有多个消息在排队等待显示。get_flashed_messages()
函数获取的消息在下次调用时不会再次返回,因此 Flash
消息只显示一次,然后就消失了。