Django memoize 每个请求

Django memoize per request

我有一个 django rest 应用程序,其中有一个函数使用一些外部数据(来自另一个服务)计算某些东西,如果不需要,我想避免加载。此数据定期更改,但对于一个请求是相同的。因此,我想在一个请求的持续时间内缓存此函数的结果(因为它在一个请求期间被多次调用)。我遇到了缓存函数结果的 https://github.com/tvavrys/django-memoize/ 库,但我只能指定时间而不是上下文,在该时间之后缓存应该失效。

我发现合理的一种可能性是以某种方式注册一个在每次请求后清除缓存的挂钩(使用delete_memoized),但我还没有找到注册这样一个挂钩的方法。

因此,我的问题是:是否可以

也许你应该试试 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.