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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With