Why decorate Jinja2 instances with @ webapp2.cached_property

The webapp2 website ( http://webapp-improved.appspot.com/api/webapp2_extras/jinja2.html ) contains a guide to using webapp2_extras.jinja2 , and the code is below.

My question is: why cache the webapp2_extras.jinja2.Jinja2 instance of the return jinja2.get_jinja2(app=self.app) ? I checked the @webapp2.cached_property code and found that it was caching the Jinja2 instance in the BaseHandler instance that would be destroyed after the request, so why cache it? Am I missing 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)
+6
source share
1 answer

You can find documentation on cached_property .

The BaseHandler class will be called often later. I understand that to avoid overhead when calling jinja2.get_jinja2(app=self.app) such a link is evaluated only the first time, and then returned many times later, that is, every time the view is called.

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

+1
source

Source: https://habr.com/ru/post/924654/


All Articles