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):
....
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.instancememoizing decorator: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:
Utility views, like
@@plone_contextand such, benefit most fromplone.memoize.view.memoize.If your expensive method is independent of the view context, use the
memoize_contextlessdecorator; this omits the view context path from the cache key: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_contextlessvariant so you store only one copy of the result.