flask入门教程(6) - 消息闪现

消息闪现

一个应用当然要有合适的反馈给用户,比如注册时可能反馈给用户:

你的用户名重复了

这时候你就会更改你的用户名,flask自然也提供了这个方法:flash

flash

使用flash函数我们可以闪现消息,现调整目录结构为:

- static
  - test.jpg
- templates
  - index.html
- app.py

这里index.html需要用到{% %}语法,注意这里面嵌入if或者for是这样的,这里以for举例:

{% for i in lst %}
<p>i</p>
{% endfor %}

这里不需要冒号,也不需要缩进,只是使用endfor结束,而if则是以endif结束。

注意flash的内部源码需要使用session,大家现在只要记住session这东西叫会话,是用来存储数据的就好,以后我们会详细讲解。

由于session需要使用密匙,那么这个密匙怎么得到呢,其实自己起一个就好,但是这肯定不随机,这时候我们可以用os.urandom函数生成密匙,在命令行输入下列命令:

python -c "print(__import__('os').urandom(24))"

接下来会输出一个随机生成的字符串,你可以复制下来作为密匙,当然你也可以直接这样:

app.config["SECRET_KEY"] = os.urandom(24)

我们继续看html

这里html中获取flash的消息需要用get_flashed_messages函数,下面是index.html的代码:

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        {% for msg in get_flashed_messages() %}
        <p>{{ msg }}</p>
        {% endfor %}
        <img src="{{ url_for('static', filename='test.jpg') }}">
    </body>
</html>

app.py使用flash闪现消息:

# app.py
import os

from flask import Flask, render_template, flash

app = Flask(__name__)
app.config["SECRET_KEY"] = os.urandom(24)

@app.route("/")
def index():
    flash("Hello World!")
    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True)

打开网页,你会看到你的消息显示在了上面:
在这里插入图片描述
当然flash还有更多功能,可以指定flash的等级,加上with_categories=true后就可以带上等级获取消息了,默认等级是message。这里是index.html改变后的代码:

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        {% for category, msg in get_flashed_messages(with_categories=true) %}
        <p>{{ category }}: {{ msg }}</p>
        {% endfor %}
        <img src="{{ url_for('static', filename='test.jpg') }}">
    </body>
</html>

加上category后的app.py如下:

# app.py
import os

from flask import Flask, render_template, flash

app = Flask(__name__)
app.config["SECRET_KEY"] = os.urandom(24)

@app.route("/")
def index():
    flash("Hello World!")
    flash("Error!", "error")
    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True)

打开网页会发现category显示出来了:
在这里插入图片描述
flash还可以根据消息类别过滤消息,这里就不展开了,可以在index.html加上参数:

category_filter=["error"]

信号

flask还为我们提供了一个函数,用作在消息发送出后发送一个信号,我们可以把这个信号连接上一个函数,也就是订阅者,就像我们之后会讲到的信号一样:

from flask import message_flashed

record = []
def record_flash_message(sender, message, category, **kwargs):
    record.append((sender, message, category, kw))
    
message_flashed.connect(record_flash_message, app)

下次见!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值