消息闪现
Flask 提供了消息闪现的功能,以使我们的应用可以向用户反馈信息。比如,当用户登录失败了,我们会提醒用户名错误或者密码错误。
在 Flask 中使用消息闪现很简单。下面我们以上一篇的例子进行说明。完整的代码在这里。
首先,让我们看一下book.py的代码:
1. # -*- coding: utf-8 -*-
3. from flask import Blueprint, url_for, render_template, request, flash, redirect
5. book_bp = Blueprint(
6. 'book',
7. __name__,
8. template_folder='../templates',
9. )
11. books = ['The Name of the Rose', 'The Historian', 'Rebecca']
14. @book_bp.route('/', methods=['GET'])
15. def index():
16. return '<h1>Hello World!</h1>'
19. @book_bp.route('/book', methods=['GET', 'POST'])
20. def handle_book():
21. _form = request.form
23. if request.method == 'POST':
24. title = _form["title"]
25. books.append(title)
26. flash("add book successfully!") # 使用 flash 反馈消息
27. return redirect(url_for('book.handle_book'))
29. return render_template(
30. 'book.html',
31. books=books
32. )
注意到,用户添加完书籍的时候,我们向用户反馈『添加书籍成功』的消息:
1. flash("add book successfully!")
但是,还有一个步骤要做,才能让用户接收到这个消息,那就是在模板中获取这个消息,通过在layout.html中使用get_flashed_messages()获取消息,layout.html代码如下:
1. <!doctype html>
2. <title>Hello Sample</title>
3. <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
5. <div class="page">
6. {% block body %} {% endblock %}
7. </div>
9. {% for message in get_flashed_messages() %}
10. {{ message }}
11. {% endfor %}
分类闪现消息
我们还可以对闪现消息进行分类,比如有些消息是正常的通知消息,而有些消息是出错消息。同样,我们需要两个步骤:
- 使用 flash() 函数的第二个参数,不使用的话,默认是 ‘message’
1. flash('add book fail', 'error')
- 接着,在模板中调用
get_flashed_messages()函数来返回这个分类,类似下面:
1. {% with messages = get_flashed_messages(with_categories=true) %}
2. {% for category, message in messages %}
3. {{category}}: {{ message }}
4. {% endfor %}
5. {% endwith %}
过滤闪现消息
过滤闪现消息在模板中可以这样用:
1. {% with error_messages = get_flashed_messages(category_filter=["error"]) %}
2. {% for error in error_messages %}
3. {{ error }}
4. {% endfor %}
5. {% endwith %}
