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消息为空。

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

被折叠的 条评论
为什么被折叠?



