为什么用@ webapp2.cached_property装饰Jinja2实例

Pau*_*l H 6 caching properties jinja2 webapp2

webapp2站点(http://webapp-improved.appspot.com/api/webapp2_extras/jinja2.html)有一个如何使用的教程webapp2_extras.jinja2,代码如下.

我的问题是:为什么缓存webapp2_extras.jinja2.Jinja2实例返回return jinja2.get_jinja2(app=self.app)?我检查了代码@webapp2.cached_property并发现它将Jinja2实例缓存在一个实例中BaseHandler,它会在请求后被销毁,所以为什么要费心去缓存呢?我在这里错过了什么吗?

import webapp2

from webapp2_extras import jinja2

class BaseHandler(webapp2.RequestHandler):

    @webapp2.cached_property
    def jinja2(self):
        # Returns a Jinja2 renderer cached in the app registry.
        return jinja2.get_jinja2(app=self.app)

    def render_response(self, _template, **context):
        # Renders a template and writes the result to the response.
        rv = self.jinja2.render_template(_template, **context)
        self.response.write(rv)

gg3*_*349 1

在这里您可以找到有关 的文档cached_property

稍后班级BaseHandler会经常被叫到。jinja2.get_jinja2(app=self.app)我的理解是,为了避免每次调用的开销,此类引用仅在第一次评估,然后多次返回,即每次调用视图时。

要在代码中查看这种情况,请参阅示例,其中每个视图都派生自同一个BaseHandler类。