Fork me on GitHub

Flask之flash

一、flash简单用法

  好的应用程序和用户界面都与反馈有关。如果用户没有得到足够的反馈,他们可能最终会讨厌该应用程序。Flask提供了一种非常简单的方法,可以通过闪烁系统向用户提供反馈。基本上,闪存系统使得可以在请求结束时记录一条消息,并在下一个(也只有下一个)请求中访问它。通常将其与布局模板结合使用以显示消息。

在使用flash过程中需要注意以下几个方面:

1、使用之前需要设置秘钥

flash是基于session来进行完成,而session中是必须要设置秘钥的,所以flash是必须要设置秘钥的。

2、设置值

设置值是通过flash('1234')这样的形式来设置的,但是假如有不同类型的值可以通过category参数来对设置的值进行分类。

from flask import Flask, flash, redirect

app = Flask(__name__)

app.secret_key = 'abcdef' @app.route(
'/login') def login(): flash('aaa') #设置基本的值 flash('bbb', category='typeb') #分类设置值 return redirect('/index') if __name__ == '__main__': app.run()

3、取值

flash中取值使用的是get_flashed_messages方法,如果需要取出指定分类的数据,输入category_filter参数即可:

from flask import Flask, flash, redirect, get_flashed_messages

app = Flask(__name__)

app.secret_key = 'abcdef'


@app.route('/login')
def login():
    flash('aaa')  # 设置基本的值
    flash('bbb', category='typeb')
    return redirect('/index')


@app.route('/index')
def index():
    print(get_flashed_messages())  # ['aaa', 'bbb']
    print(get_flashed_messages(category_filter='typeb'))  # ['bbb']
    return 'index'


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

需要注意的是,取值是通过session.pop()这样的方法,一旦第一次取走后,访问index页面,之前的值就不存在了,除非再重新进行login函数赋值操作。

所以,flash就是一个基于session来实现的保存数据集合的一种技术,它的特点就是使用一次数据就会被删除。

二、应用场景

一般的应用场景就是在跳转页面后提示信息,比如,登录成功或者失败之类的提示语。

from flask import Flask, flash, redirect, get_flashed_messages, request, render_template

app = Flask(__name__)

app.secret_key = 'abcdef'


@app.route('/login')  # 请求http://127.0.0.1:5000/login?username=zhangsan
def login():
    username = request.args['username']
    print(username)
    if username == 'zhangsan':
        flash('登录成功')
        return redirect('/index')
    else:
        flash('登录失败')  # 设置基本的值
        return render_template('login.html')


@app.route('/index')
def index():
    print(get_flashed_messages())  # ['登录成功']
    return 'index'


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

当然你可以直接将flash的消息渲染在模板文件中,只需要使用get_flashed_messages方法即可。

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ get_flashed_messages() }} <!--闪现消息-->
</body>
</html>

 

 

 

 

 

posted @ 2020-07-05 11:24  iveBoy  阅读(791)  评论(0编辑  收藏  举报
TOP