Flask源码阅读(六)——Flash消息

本文探讨了Flask框架中的核心特性——Flash消息,用于在响应间传递状态更新通知,如确认、警告或错误提示。通过调用flash()函数存储消息,并在模板中使用get_flashed_messages()函数进行渲染。源码分析揭示了flash()如何在session中存储消息,以及get_flashed_messages()如何获取并处理这些消息。

1.flash消息这种功能,是Flask的核心特性。用于在下一个响应中显示一个消息,让用户知道状态发生了变化。可以使确认消息,警告或者错误提醒。

2.仅调用flash()函数并不能把消息显示出来,程序使用的模板要渲染这些消息。Flask把get_flashed()函数开放给模板,用来获取并渲染消息。

3.源码

def flash(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 :func:`get_flashed_messages`.

    :param message: the message to be flashed.
    """
    session['_flashes'] = (session.get('_flashes', [])) + [message]


def get_flashed_messages():
    """Pulls all flashed messages from the session and returns them.
    Further calls in the same request to the function will return
    the same messages.
    """
    flashes = _request_ctx_stack.top.flashes
    if flashes is None:
        _request_ctx_stack.top.flashes = flashes = \
            session.pop('_flashes', [])
    return flashes

flash()函数中,存于session的’_flash’被赋值为“空”的’_flash’+message,message为要提醒的信息。并且,源码注释部分提到,模板中必须调用get_flashed_message()函数。
再来看get_falshed_messange()函数。首先,将flashes消息赋值为_request_ctx_stack这个LocalStack对象获取堆栈顶部的flashes消息,就是前一个推出去的flash消息。如果flashes消息为空,则_request_ctx_stack这个LocalStack对象获取堆栈顶部的flash消息为空。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值