Getting Started with Flask (8): Flash

8. Flash

Flask's flash system provides a nice way of giving feedback.

The basic way the flashing system works is: only in the next request will the messages recorded at the end of the previous request be accessed. Generally we use the flashing system in combination with layout templates.

Requirement: There are two functions login and index, a person is making a request to the login page, login generates an error, puts it in the session, jumps to the index to display the error, and then removes the session, and this error can only be executed once (That is, let you watch it once) This thing can be realized with flash.

Examples are as follows:

from flask import Flask,session,flash,get_flashed_messages


app = Flask(__name__)
app.secret_key = "asklfnasfgasnklsdk"


@app.route("/x1", methods=["GET", "POST"])
def login():
    # session['msg'] = "回复哈哈哈哈哈哈"  #这是基于session做的
    flash("闪现消息1", category='x1')  #这是另一种方法,设置flash,这个内部也是基于session做的,flash其实就是把这个值设置到session上
    flash("闪现消息2", category='x2')  #category表示对数据进行分类
    return "视图函数x1"


@app.route("/x2", methods=["GET", "POST"])
def index():
    data = get_flashed_messages(category_filter=['x1']) #这个是取上面我们设置的类似于错误信息的东西,这个其实就是在session上把他上面设置的值拿到并且删除
    #category_filter = ['x1'] 这个意思就是取x1那个对应的数据,两个都要拿就category_filter = ['x1','x2']
    print(data)
    # msg = session.pop('msg')  #这个拿完以后就没有了,这是基于session实现的,看完以后就删除了
    return "视图函数x2"

if __name__ == '__main__':
    app.run()

Reference:
http://www.pythondoc.com/flask/patterns/flashing.html
https://www.cnblogs.com/1996-11-01-614lb/p/8975842.html

Guess you like

Origin blog.csdn.net/qq_43745578/article/details/129132145