【发布时间】:2020-06-17 20:35:29
【问题描述】:
我正在处理的项目中的一种方法如下所示:
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()
【问题讨论】:
标签: django django-cache