我有一个 django rest 应用程序,其中有一个函数可以使用一些外部数据(来自另一个服务)计算某些东西,如果不需要,我想避免加载。此数据定期更改,但对于一个请求是相同的。因此,我想在一个请求的持续时间内缓存这个函数的结果(因为它在一个请求期间被多次调用)。我遇到了https://github.com/tvavrys/django-memoize/库,它缓存函数结果,但我只能指定一个时间而不是一个上下文,在此之后缓存应该失效。
我认为合理的一种可能性是在每次请求后以某种方式注册一个清除缓存的钩子(Hook)(使用 delete_memoized
),但我还没有找到注册这种钩子(Hook)的方法。
因此,我的问题是:是否有可能
最佳答案
也许你应该试试 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.
关于Django memoize 每个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52312788/