• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

flask框架:闪现消息提示

武飞扬头像
李恩泽的技术博客
帮助1

前言

这几年一直在it行业里摸爬滚打,一路走来,不少总结了一些python行业里的高频面试,看到大部分初入行的新鲜血液,还在为各样的面试题答案或收录有各种困难问题

于是乎,我自己开发了一款面试宝典,希望能帮到大家,也希望有更多的Python新人真正加入从事到这个行业里,让python火不只是停留在广告上。

微信小程序搜索:Python面试宝典

也可关注微信公众号,不定时发送各类有趣猎奇的技术文章:Python编程学习

闪现

类似django的message组件

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

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

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

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


基操勿6

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

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfijfa
系列文章
更多 icon
同类精品
更多 icon
继续加载