Flask-10-消息闪现

一、什么是消息闪现

一个好的应用和用户接口都有良好的反馈,否则到后来用户就会讨厌这个应用。 Flask 通过闪现系统来提供了一个易用的反馈方式。闪现系统的基本工作原理 是在请求结束时记录一个消息,提供且只提供给下一个请求使用。通常通过一 个布局模板来展现闪现的消息
闪现系统的基 本工作方式是:在且只在下一个请求中访问上一个请求结束时记录的消息。一般我们 结合布局模板来使用闪现系统。注意,浏览器会限制 cookie 的大小,有时候网络服 务器也会。这样如果消息比会话 cookie 大的话,那么会导致消息闪现静默失败。

二、基础用法

2.1 生成一个密钥

Flask在某些情况下,会要求生成一个密钥,这个密钥用于cookie、消息闪现等场景。
python命令行生成一个密钥

python -c "import secrets; print(secrets.token_hex())"
Flask-10-消息闪现
image.png

2.2 配置密钥

# 导入falsk
from flask import Flask, render_template, jsonify, request, flash, redirect, url_for

# 通过导入的falsk,创建一个app
app = Flask(__name__)
# 通过 python -c "import secrets; print(secrets.token_hex())" 来实现
app.secret_key = "16623b4eb38efb00f2b8e7f5359f80d1826caf0c77506856e1e12cfc53b0dc83"


# 路由
@app.route('/')
def index():
    return render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] == 'admin':
            flash('登录成功')
            return render_template("index.html")
        else:
            flash('登录失败')
            error = '用户名错误'
            # 另一种跳转方式
            return redirect(url_for('index'))
    return render_template('login.html', error=error)


# 开启运行
if __name__ == '__main__':
    app.run(debug=True)
    """
    debug,是否开启调试模式,开启后,重新启动程序,当再次修改Python代码后,会立即启动
    port,启动指定服务器的端口号,默认是5000
    host,主机,默认是127.0.0.1;如果指定0.0.0.0代表本机的所以IP    
    """

2.3 模板index.html

<!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>

2.4 模板login.html

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

2.5 代码解释

从登录页面中login.html中登录后,会进入视图函数login中,其中,在试图函数中增加了flash("要传递的内容")方法,传递消息给下一个请求;登录成功与失败,都会跳转到index.html页面中,,然后再index.html模板中通过get_flashed_messages()方法进行获取,然后展示就能得到消息闪现出的内容。

三、闪现消息的类别

闪现消息还可以指定类别,如果没有指定,那么缺省的类别为 ‘message’ 。不同的 类别可以给用户提供更好的反馈。例如错误消息可以使用红色背景。
使用 flash() 函数可以指定消息的类别:

flash('闪现消息的内容''error'
# 这里第二个参数,就是类别,有意义即可

3.1 视图函数

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] == 'admin':
            # 第二个参数指定了类别
            flash('登录成功''ok')
            return render_template("index.html")
        else:
            # 第二个参数指定了类别
            flash('登录失败''err')
            error = '用户名错误'
            return redirect(url_for('index'))
    return render_template('login.html', error=error)

3.2 模板index.html

get_flashed_messages(with_categories=true)指定使用消息列表,那获取消息时就能得到消息类别了,这里类别与页面中的样式组合起来了。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>

    <style>
        .ok {
            color: blue;
        }

        .err {
            color: red;
        }
    </style>

</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() 的 结果。这个功能有助于在不同位置显示不同类别的消息。

# 这里过滤到error分类
{% with errors = get_flashed_messages(category_filter=["error"]) %}
    {% if errors %}
        <div class="alert-message block-message error">
            <a class="closehref="#">×</a>
            <ul>
                {%- for msg in errors %}
                    <li>{{ msg }}</li>
                {% endfor -%}
            </ul>
        </div>
    {% endif %}
{% endwith %}


原文始发于微信公众号(Python之家):Flask-10-消息闪现

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/198263.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!