Flask消息闪现

Flask消息闪现

一个好的应用和用户界面都需要良好的反馈。如果用户得不到足够的反馈,那么应用最终会被用户唾弃。

Flask 的闪现系统提供了一个良好的反馈方式。

闪现系统的基本工作方式是:

  • 在且只在下一个请求中访问上一个请求结束时记录的消息。
  • 一般我们 结合布局模板来使用闪现系统。
  • 注意,浏览器会限制 cookie 的大小,有时候网络服 务器也会。这样如果消息比会话 cookie 大的话,那么会导致消息闪现静默失败。

简单的例子

以下是一个完整的示例:

from flask import Flask, flash, redirect, render_template, \
     request, url_for

app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

@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' or \
           request.form['password'] != 'secret':
            error = 'Invalid credentials'
        else:
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    return render_template('login.html', error=error)

上面py文件比如保存为flashtest.py

以下是实现闪现的 layout.html 模板:

注,html模板默认放在项目的templates目录下。

<!doctype html>
<title>My Application</title>
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}
{% block body %}{% endblock %}

以下是继承自 layout.htmlindex.html 模板:

{% extends "layout.html" %}
{% block body %}
  <h1>Overview</h1>
  <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>
{% endblock %}

以下是同样继承自 layout.htmllogin.html 模板:

{% extends "layout.html" %}
{% block body %}
  <h1>Login</h1>
  {% if error %}
    <p class=error><strong>Error:</strong> {{ error }}
  {% endif %}
  <form method=post>
    <dl>
      <dt>Username:
      <dd><input type=text name=username value="{{
          request.form.username }}">
      <dt>Password:
      <dd><input type=password name=password>
    </dl>
    <p><input type=submit value=Login>
  </form>
{% endblock %}

运行应用

>set FLASK_APP=flashtest.py
>python -m flask run

访问默认的127.0.0.1:5000可见闪现效果:

flask_flash

闪现消息的类别

闪现消息还可以指定类别,如果没有指定,那么缺省的类别为 'message' 。不同的 类别可以给用户提供更好的反馈。例如错误消息可以使用红色背景。(样式要自己根据class=类别额外去写好css)

使用 flash() 函数可以指定消息的类别:

flash(u'Invalid password provided', 'error')

注: 这一行是添加在 error= 'Invalid credentials' 这一行之后:

@app.route('/login', methods=['GET','POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or \
           request.form['password'] != 'secret':
            error= 'Invalid credentials'
            flash(u'Invalid password provided', category='error')
        else:
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    return render_template('login.html',error=error)

模板中的 get_flashed_messages() 函数也应当返回类别,显示消息的循环 也要略作改变:

{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    <ul class=flashes>
    {% for category, message in messages %}
      <li class="{{ category }}">{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

上例展示如何根据类别渲染消息,还可以给消息加上前缀,如 <strong>{{ category }}:</strong>

<!DOCTYPE html>
<title>My Application</title>
{% with messages = get_flashed_messages(with_categories=True) %}
  {% if messages %}
    <ul class=flashes>
    {% for category, message in messages %}
      <li class="{{ category }}"><strong>{{ category }}:</strong>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}
{% block body %}{% endblock %}

注:虽然可以拿到类别,但是要依据类别来写li标签的样式,让错误信息显示是红色背景还要自己额外去写好样式哦。

过滤闪现消息

你可以视情况通过传递一个类别列表来过滤 get_flashed_messages() 的 结果。这个功能有助于在不同位置显示不同类别的消息。

{% with errors = get_flashed_messages(category_filter=["error"]) %}
{% if errors %}
<div class="alert-message block-message error">
  <a class="close" href="#">×</a>
  <ul>
    {% for msg in errors %}
    <li>{{ msg }}</li>
    {% endfor %}
  </ul>
</div>
{% endif %}
{% endwith %}

flask.flash()get_flashed_messages() 官网说明如下:

Message Flashing

  • flask.flash(message, category='message')

    Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call get_flashed_messages().

    Parameters:

    message – the message to be flashed.

    category – the category for the message.

    The following values are recommended:

    'message' for any kind of message,

    'error' for errors,

    'info' for information messages and 'warning' for warnings.

    However any kind of string can be used as category.

  • flask.get_flashed_messages(with_categories=False, category_filter=[])

    Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when with_categories is set to True, the return value will be a list of tuples in the form (category, message) instead. Filter the flashed messages to one or more categories by providing those categories in category_filter. This allows rendering categories in separate html blocks. The with_categories and category_filter arguments are distinct: with_categories controls whether categories are returned with message text (True gives a tuple, where False gives just the message text). category_filter filters the messages down to only those matching the provided categories.

    See 消息闪现 for examples.

    Parameters:

    with_categories – set to True to also receive categories.

    category_filter – whitelist of categories to limit return values

从官网里可以看出,flash() 函数:

  • 第一个参数是你将要放进去的字符串消息,

  • 第二个默认参数category,代表消息的类别,默认为message(消息,普通)。

get_flashed_messages() 两个默认参数,第一个是类别控制开关,默认是False。

  • 类别控制是否带消息文本返回类别:
    • True给出一个tuple,元祖中给出两个值,分别是消息文本和类别;
    • False只给出消息文本,不返回类别。

文:铁乐与猫

2018-9-6

参考

Flask-消息队列

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Flask框架提供了闪现消息提示的功能,可以在请求之间传递消息。这些消息可以是成功或错误的消息,可以在下一个请求中显示给用户。闪现消息通常用于表单验证或用户登录后的欢迎消息等场景。 以下是一个简单的示例,演示如何使用闪现消息提示: ```python from flask import Flask, flash, redirect, render_template, request, url_for app = Flask(__name__) app.secret_key = 'some_secret_key' @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] if username == 'admin' and password == 'password': flash('登录成功!', 'success') return redirect(url_for('index')) else: flash('用户名或密码错误!', 'error') return render_template('login.html') if __name__ == '__main__': app.run(debug=True) ``` 在上面的示例中,我们首先导入了Flask框架和flash函数。然后,我们定义了一个应用程序,并设置了一个秘密密钥。接下来,我们定义了两个路由,一个用于显示主页,另一个用于处理登录请求。在登录路由中,我们首先检查请求的方法是否为POST,如果是,则获取用户名和密码。如果用户名和密码正确,则使用flash函数显示成功消息,并重定向到主页。否则,我们显示错误消息。 在HTML模板中,我们可以使用以下代码来显示闪现消息: ```html {% with messages = get_flashed_messages() %} {% if messages %} <ul class="flashes"> {% for message in messages %} <li class="{{ message[1] }}">{{ message[0] }}</li> {% endfor %} </ul> {% endif %} {% endwith %} ``` 在上面的代码中,我们首先使用get_flashed_messages函数获取所有闪现消息。然后,我们使用一个循环来遍历所有消息,并将它们显示为一个无序列表。每个消息都有一个类别,可以是success、error、warning或info。我们可以使用这些类别来为每个消息设置不同的样式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

铁乐与猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值