您的位置:首页 > 其它

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

2016-01-08 12:49 274 查看

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消息为空。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  源码