我正在研究的项目中的一种方法如下:
from django.core.cache import cache
from app import models
def _get_active_children(parent_id, timestamp):
children = cache.get(f"active_seasons_{parent_id}")
if children is None:
children = models.Children.objects.filter(parent_id=parent_id).active(
dt=timestamp
)
cache.set(
f"active_children_{parent_id}",
children,
60 * 10,
)
return children
问题是,我不希望通过命令行(在任务内部)调用此方法时发生缓存。所以我想知道是否有办法禁用这种形式的缓存?
理想情况下,我想使用上下文管理器,以便忽略上下文内的任何缓存调用(或将其推送到不会影响我的主Redis缓存的DummyCache / LocalMem缓存)。
我已经考虑过通过这些方法来保持skip_cache=True
的功能,但这非常脆弱,我敢肯定还有一个更优雅的解决方案。另外,我尝试使用mock.patch
,但不确定在测试类之外是否可以使用。
我理想的解决方案如下所示:
def task():
...
_get_active_children(parent_id, timestamp):
with no_cache:
task()
我有一个解决方案(但我认为那里有一个更好的解决方案: