Flask闪现

98 阅读2分钟

闪现

类似django的message组件

一个好的应用和用户界面都需要良好的反馈。如果用户得不到足够的反馈,那么应用最终会被用户唾弃,Flask 的 闪现系统提供了一个良好的反馈方式

闪现系统的基本工作方式是:只在下一个请求中展示上一个请求结束时记录的消息,底层是通过session来完成

一般我们结合布局模板来使用闪现系统,比如a页面操作出错,跳转到b页面,在b页显示a页面的错误信息

注意,浏览器会限制 cookie 的大小,有时候网络服务器也会。 这样如果消息比会话 cookie 大的话,那么会导致消息闪现静默失败


demo

比如一个登陆视图如下,当判断用户账号密码不符合规则时,将抛出闪现提示错误信息

@app.route("/")
def login():
  	if request.method == "GET":
        return render_template("login.html") # 返回模版页面
    if request.method == "POST":
        username = request.form.get("username") # 校验模版数据
        if username != "Zege":
            flash("This is't Zege, sry!", category="error")
        return render_template("login.html")

模版页面展示闪现消息,使用get_flashed_messages(with_categories=true)方法

{% with messages = get_flashed_messages() %}
    {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
        <li>{{ message }}</li>
        {% endfor %}
        </ul>
    {% endif %}
{% endwith %}

分类展示

不光如此,flask的闪现还支持分类展示有好消息、坏消息与默认消息,默认为category="message",还有error、info、warning

def flash(message, category="message"):
  	...
    :param category: the category for the message.  The following values
                     are recommended: ``'message'`` for any kind of message,
                     ``'error'`` for errors, ``'info'`` for information
                     messages and ``'warning'`` for warnings.  However any
                     kind of string can be used as category.
    ...

比如一个闪现消息设置了category,那么使用如下

flash("This is't Zege, sry!", category="info")

模版页面如果想获取分类以搭配bootstrap使用,那么可以使用get_flashed_messages(with_categories=true)

{% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}
        {% for category,message in messages %}
        <li>{{ message }}:{{ category }}</li>
        {% endfor %}
    {% endif %}
{% endwith %}

过滤展示

闪现消息还支持通过指定的消息类型进行过滤,通过get_flashed_messages(category_filter=["info"])完成


比如返回了一堆消息,但是您只想看到error分类下的闪现消息

flash("error", category="error")
flash("message", category="message")
flash("info", category="info")
flash("warning", category="warning")

模版页面进行过滤筛选

{% with messages = get_flashed_messages(category_filter=["error"]) %}
    {% if messages %}
        {% for message in messages %}
        <li>{{ message }}</li>
        {% endfor %}
    {% endif %}
{% endwith %}