Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why decorate Jinja2 instances with @webapp2.cached_property

The webapp2 site (http://webapp-improved.appspot.com/api/webapp2_extras/jinja2.html) has a tutorial on how to use webapp2_extras.jinja2, and the code is below.

My question is: why cache the webapp2_extras.jinja2.Jinja2 instance return by return jinja2.get_jinja2(app=self.app)? I checked the code of @webapp2.cached_property and found that it caches the Jinja2 instance in a instance of BaseHandler, which will be destroyed after the request, so why bother to cache it? Did I miss something here?

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)
like image 213
Paul H Avatar asked Sep 05 '12 15:09

Paul H


1 Answers

Here you can find the documentation about cached_property.

The BaseHandler class will be later on called often. My understanding is that to avoid the overhead of calling jinja2.get_jinja2(app=self.app) each time, such reference is evaluated the first time only, and then returned many times later on, i.e. every time a view is called.

To see this happen in code, see this example, where each view is derived from the same BaseHandler class.

like image 199
gg349 Avatar answered Sep 30 '22 01:09

gg349