Flask 学习-65.消息闪现 flash

前言

一个好的应用和用户界面都需要良好的反馈。如果用户得不到足够的反馈,那么应用 最终会被用户唾弃。
Flask 的闪现系统提供了一个良好的反馈方式。闪现系统的基 本工作方式是:在且只在下一个请求中访问上一个请求结束时记录的消息。

设置 flash()

flask提供了一个非常有用的flash()函数,它可以用来“闪现”需要提示给用户的消息,比如当用户登录成功后显示“欢迎回来!”。
在视图函数调用flash()函数,传入消息内容,flash()函数把消息存储在session中,我们需要在模板中使用全局函数get_flashed_messages()获取消息并将它显示出来。
flash是基于session, 所以必须要设置秘钥 secret_key

flash()函数源代码

  • message 消息内容
  • category 消息类别,可以不用传,默认缺省值"message"
def flash(message: str, category: str = "message") -> None:
    """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 :func:`get_flashed_messages`.

    .. versionchanged:: 0.3
       `category` parameter added.

    :param message: the message to be flashed.
    :param 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.
    """
    # Original implementation:
    #
    #     session.setdefault('_flashes', []).append((category, message))
    #
    # This assumed that changes made to mutable structures in the session are
    # always in sync with the session object, which is not true for session
    # implementations that use external storage for keeping their keys/values.
    flashes = session.get("_flashes", [])
    flashes.append((category, message))
    session["_flashes"] = flashes
    message_flashed.send(
        current_app._get_current_object(),  # type: ignore
        message=message,
        category=category,
    )

基本使用示例

@app.route('/login')
def login():
    flash('welcome to back!')
    return {'msg': 'ok'}

get_flashed_messages 获取flash 消息

get_flashed_messages(with_categories=False, category_filter=()),

  • with_categories 默认False只返回消息内容,设置True会以元祖返回消息类别和内容
  • 如果不传递 category_filter,取出上面存储的所有分类传递的值
def get_flashed_messages(
    with_categories: bool = False, category_filter: t.Iterable[str] = ()
) -> t.Union[t.List[str], t.List[t.Tuple[str, str]]]:
    """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 :doc:`/patterns/flashing` for examples.

    .. versionchanged:: 0.3
       `with_categories` parameter added.

    .. versionchanged:: 0.9
        `category_filter` parameter added.

    :param with_categories: set to ``True`` to also receive categories.
    :param category_filter: filter of categories to limit return values.  Only
                            categories in the list will be returned.
    """
    flashes = _request_ctx_stack.top.flashes
    if flashes is None:
        _request_ctx_stack.top.flashes = flashes = (
            session.pop("_flashes") if "_flashes" in session else []
        )
    if category_filter:
        flashes = list(filter(lambda f: f[0] in category_filter, flashes))
    if not with_categories:
        return [x[1] for x in flashes]
    return flashes

这个flash只能一个视图函数中取,只要有一个视图函数取过了,那其他视图函数就不能获取,本质是调用session.pop("_flash")
但是在同一个视图函数里面可以无限的取值。

使用示例

from flask import Flask, current_app, flash, get_flashed_messages


app = Flask(__name__)
app.secret_key = 'yoyo'


@app.route('/login')
def login():
    flash('welcome to back!')
    return {'msg': 'ok'}


@app.route('/get')
def get():
    msg = get_flashed_messages()
    return {'msg': msg}


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

先访问/login,就会有闪现消息,再访问/get取值

category 消息分类参数使用

category 设置消息类别

@app.route('/login')
def login():
    flash('welcome to back!', category='login')
    flash('admin', category='user')
    return {'msg': 'ok'}

with_categories默认False 得到的值

['welcome to back!', 'admin']

with_categories设置为True

@app.route('/get')
def get():
    msg = get_flashed_messages(with_categories=True)
    print(msg)
    return {'msg': msg}

得到msg值

[('login', 'welcome to back!'), ('user', 'admin')]

category_filter 参数可以设置过滤消息

@app.route('/get')
def get():
    msg = get_flashed_messages(with_categories=True, category_filter=['login'])
    print(msg)
    return {'msg': msg}

过滤后的结果

[('login', 'welcome to back!')]

flash 消息闪现一般用在前端页面上,比如当用户登录成功后显示“欢迎回来!”,可以用来“闪现”需要提示给用户的消息。
在模板中调用get_flashed_messages()相关示例参考官方文档https://dormousehole.readthedocs.io/en/latest/patterns/flashing.html

posted @   上海-悠悠  阅读(333)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-09-09 python测试开发django-122.bootstrap模态框(modal)学习
2021-09-09 python测试开发django-121.bootstrap-table弹出模态框修表格数据提交
2020-09-09 2020年第五期《python接口自动化+测试开发》课程,10月11号开学(火热报名中!)
2020-09-09 pytest文档55-plugins插件开发
点击右上角即可分享
微信分享提示