Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching view/viewlet methods return values by self.request

Tags:

plone

plone.memoize packages provides handy helper functions for caching values of various functions.

What is the best practice of caching values of view/viewlet methods for the lifetime of the current HTTP Request (self.request). This is not entirely clear from plone.memoize documentation.

Example:

   class MyView(grok.View):

         # cache this by self.request
         def getExpensiveFunction(self):
               ....
like image 992
Mikko Ohtamaa Avatar asked Apr 20 '26 08:04

Mikko Ohtamaa


1 Answers

Since a BrowserPage view instance's lifetime is normally the duration of the request already, you generally may just as well use the plone.memoize.instance memoizing decorator:

from plone.memoize.instance import memoize

class MyView(grok.View):

    @memoize
    def getExpensiveFunction(self):
        # ....

After all, the BrowserPage is normally looked up for a given URL, instanciated when looked up, and discarded when the view has been produced. A new request will produce a new instance.

The view memoizer stores the cache on the current request, and adds the current context path (or the id of the context, if there is no path) as a cache key. If the view is looked up in different places during a request you can use that instead of the instance memoizer:

from plone.memoize.view import memoize

class MyView(grok.View):

    @memoize
    def getExpensiveFunction(self):
        # ....

Utility views, like @@plone_context and such, benefit most from plone.memoize.view.memoize.

If your expensive method is independent of the view context, use the memoize_contextless decorator; this omits the view context path from the cache key:

from plone.memoize.view import memoize_contextless

class MyView(grok.View):

    @memoize_contextless
    def getExpensiveFunction(self):
        # ....

So, if .getExpensiveFunction() would return the same information regardless of what the context of this view is (be it the site root or somewhere deep in the content tree), use the _contextless variant so you store only one copy of the result.

like image 170
Martijn Pieters Avatar answered Apr 21 '26 21:04

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!