Search code examples
djangodjango-rest-frameworkmemoization

Django memoize per request


I have a django rest application in which there is a function which calculates something using some external data (from another service) I want to avoid loading if not required. This data changes regularly, but is the same for one request. Therefore, I want to cache the result of this function (since it is called multiple times during one request) for the duration of exactly one request. I've come across the https://github.com/tvavrys/django-memoize/ library, which caches function results, but I can only specify a time and not a context after which the cache should be invalidated.

One possibility I found reasonable is to somehow register a hook which clears the cache after every request (using delete_memoized), but I have not found a method to register such a hook.

Therefore, my question is: Is it possible to either

  • execute some code after a response has been rendered (→ clearing the cache), or
  • tell django to cache a function result for exactly one request (using some other library?)

Solution

  • Maybe you should try with cached_property

    The @cached_property decorator caches the result of a method with a single self argument as a property. The cached result will persist as long as the instance does, so if the instance is passed around and the function subsequently invoked, the cached result will be returned.