python - flask 中的 template_rendered 函数
PHP中文网
PHP中文网 2017-04-18 09:41:06
0
2
545

一个 Flask 初学者的疑问。

大家都知道在 Flask 中我们可以通过 render_template 函数来实现渲染模板。在学习过程中意外发现 Flask 下包含了一个与其命名非常相似的 template_rendered 函数。十分的好奇,查了一下文档,文档是这么写的:

flask.template_rendered

This signal is sent when a template was successfully rendered.
The signal is invoked with the instance of the template as template and the context as dictionary (named context).

看来应该是在模板成功渲染后返回一个字典。
但是文档里写的具体使用场景我不是非常理解,所以想请教各位一下,究竟这个函数应在什么情况下使用,该怎么使用呢?

from flask import template_rendered
from contextlib import contextmanager

@contextmanager
def captured_templates(app):
    recorded = []
    def record(sender, template, context, **extra):
        recorded.append((template, context))
    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(2)
阿神

这是一个信号,每当有模板渲染就会执行。你可以订阅这个信号得到它返回的值。
ps:除了调试,我想不到有什么情景下会使用。

PHPzhong

template_rendered信号是Flask核心信号。

当一个模版成功地渲染,这个信号会被发送。这个信号与模板实例 template 和上下文的词典(名为 context )一起调用。

这篇博客作了具体说明 https://segmentfault.com/a/11...

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!