Web开发——Flask框架python_flask

Flask框架——消息闪现

2022-07-21  本文已影响0人  白巧克力LIN

上篇文章我们学习了Flask框架——flask-caching缓存,这篇文章我们来学习Flask框架——flash消息闪现。

良好的web应用程序中需要及时向用户提供反馈信息,例如:当用户输入信息点击提交后,网页会提示是否提交成功或提交信息有误等。

Flask框架通过闪现系统提供了一个简单的反馈方式。其基本工作原理为:在当前请求结束时记录一个消息,提供给当前请求或者下一个请求使用。例如:用户在A页面中操作出错后跳转到B页面,在B页面中展示了A页面的错误信息。这时就可以通过消息闪现将错误信息传递给B页面。

使用消息闪现

Flask框架提供了flash()方法来实现消息闪现,在视图函数使用flash()方法将消息传递到下一个请求,这个请求一般是模板。

flash()方法语法结构为:

flash(message,category)

其中:

注意:使用消息闪现时,需要配置SECRET_KEY的值,该值可以是任意字符。

示例代码如下:

from flask import Flask, render_template, request, flash

app = Flask(__name__)
app.config['SECRET_KEY']='sfasf'                #配置SECRET_KEY,该值为任意字符

@app.route('/',methods=['GET','POST'])
def flash_message():
    if request.method=='POST':
        username=request.form.get('username')     #获取提交的username值
        if username=='admin':                   #验证是否为admin
            flash('验证成功')                   #使用flash方法传递信息
            return render_template('index.html')    #使用render_template()方法渲染模板index.html
        else:
            flash('验证失败')                   #使用flash方法传递信息
            return render_template('index.html')    #使用render_template()方法渲染模板index.html
    return render_template('login.html')        #使用render_template()方法渲染模板login.html

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

这里我们简单地通过获取用户填写信息进行判断是否正确来传递信息,在login.html模板代码为:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="{{ url_for('flash_message') }}" method="post">
    <p><input type="text" name="username" placeholder="输入用户名"></p>
    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>

创建一个form表单并绑定上面视图函数中的flash_message(),创建文本框和按钮完成一个简单的提交网页。

在index.html模板中,使用get_flashed_messages()方法来获取消息,代码如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
{% with messages=get_flashed_messages() %}      {# 使用get_flashed_messages()方法获取消息#}
    {% if messages %}                       
        {% for message in messages %}
            {{ message }}
        {% endfor %}
    {% endif %}
{% endwith %}
</body>
</html>

注意:使用get_flashed_messages()方法获取的消息以元组的方式来保存,所以可以通过for循环来获取。

启动我们的flask程序,访问http://127.0.0.1:5000/,如下图所示:


当我们输入admin并点击提交,就会跳转网页,该网页显示内容为:验证成功;

当我们输入其他字符点击提交,就会跳转网页,该网页显示内容为:验证失败。

消息闪现分类

使用flash()方法时,我们可以传递category参数,其值可以为error(错误)、info(信息)、warning(警告),示例代码如下所示:

from flask import Flask, render_template, request, flash

app = Flask(__name__)
app.config['SECRET_KEY']='sfasf'                #配置SECRET_KEY,该值为任意字符

@app.route('/',methods=['GET','POST'])
def flash_message():
    if request.method=='POST':
        username=request.form.get('username')     #获取提交的username值
        if username=='admin':                   #验证是否为admin
            flash('验证成功','info')             #使用flash方法传递信息,闪现类型为:info
            return render_template('index.html')    #使用render_template()方法渲染模板index.html
        else:
            flash('验证失败','error')            #使用flash方法传递信息,闪现类型为:error
            return render_template('index.html')    #使用render_template()方法渲染模板index.html
    return render_template('login.html')        #使用render_template()方法渲染模板login.html

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

在index.html模板中,在使用get_flashed_messages()时,需要传递with_categories参数,其值为true,表示接收闪现类型,代码如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
{% with messages=get_flashed_messages(with_categories=true) %}      {#使用get_flashed_messages()方法#}
    {% if messages %}
        <ul>
            {% for category , message in messages %}
                <li class="{{ category }}">{{ message }}</li>
            {% endfor %}
        </ul>
    {% endif %}
{% endwith %}
</body>
</html>

过滤闪现消息

当我们在视图函数中设置了多个闪现,这时我们可以在模板文件中使用get_flashed_messages()方法时传递category_filter参数来选择我们需要的展示的闪现消息,例如我们在上面的视图函数中flash('验证成功','info')代码下添加下面flash()闪现代码:

from flask import Flask, render_template, request, flash

app = Flask(__name__)
app.config['SECRET_KEY']='sfasf'                #配置SECRET_KEY,该值为任意字符

@app.route('/',methods=['GET','POST'])
def flash_message():
    if request.method=='POST':
        username=request.form.get('username')     #获取提交的username值
        if username=='admin':                   #验证是否为admin
            flash('验证成功','info')             #使用flash方法传递信息,闪现类型为:info
            flash('请不要随意相信任何广告','warning')       #使用flash方法传递信息,闪现类型为:warning
            return render_template('index.html')    #使用render_template()方法渲染模板index.html
        else:
            flash('验证失败','error')            #使用flash方法传递信息,闪现类型为:error
            return render_template('index.html')    #使用render_template()方法渲染模板index.html
    return render_template('login.html')        #使用render_template()方法渲染模板login.html

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

在index.html模板文件中,代码如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
{% with messages=get_flashed_messages(category_filter=['warning']) %}   {#使用get_flashed_messages()方法#}
    {% if messages %}
        {% for  message in messages %}
            {{ message }}
        {% endfor %}
    {% endif %}
{% endwith %}
</body>
</html>

这里我们过滤选择了warning类型的闪现类型,启动flask程序,访问http://127.0.0.1:5000/

当我们输入admin并点击提交,就会跳转网页,该网页显示内容为:请不要随意相信任何广告;

注意:信息不能比Cookie大,否则会导致闪现静默失败。

好了,Flask框架——消息闪现就讲到这里了,感谢观看,下篇文章我们继续学习Flask框架的其他知识。

公众号:白巧克力LIN

该公众号发布Python、数据库、Linux、Flask、自动化测试、Git等相关文章!

上一篇 下一篇

猜你喜欢

热点阅读