Flask 学习-65.消息闪现 flash

2022-09-19 15:43:26 浏览数 (1)

前言

一个好的应用和用户界面都需要良好的反馈。如果用户得不到足够的反馈,那么应用 最终会被用户唾弃。 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, )

基本使用示例

代码语言:javascript复制
@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”) 但是在同一个视图函数里面可以无限的取值。

使用示例

代码语言:javascript复制
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 设置消息类别

代码语言:javascript复制
@app.route('/login')
def login():
    flash('welcome to back!', category='login')
    flash('admin', category='user')
    return {'msg': 'ok'}

with_categories默认False 得到的值

代码语言:javascript复制
['welcome to back!', 'admin']

with_categories设置为True

代码语言:javascript复制
@app.route('/get')
def get():
    msg = get_flashed_messages(with_categories=True)
    print(msg)
    return {'msg': msg}

得到msg值

代码语言:javascript复制
[('login', 'welcome to back!'), ('user', 'admin')]

category_filter 参数可以设置过滤消息

代码语言:javascript复制
@app.route('/get')
def get():
    msg = get_flashed_messages(with_categories=True, category_filter=['login'])
    print(msg)
    return {'msg': msg}

过滤后的结果

代码语言:javascript复制
[('login', 'welcome to back!')]

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

0 人点赞