Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?)
like image 474
Lukor Avatar asked Oct 28 '25 22:10

Lukor


1 Answers

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.

like image 95
juanmhidalgo Avatar answered Oct 31 '25 11:10

juanmhidalgo



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!