【问题标题】:Django disable low level caching with context managerDjango 使用上下文管理器禁用低级缓存
【发布时间】: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


    【解决方案1】:

    我有一个解决方案(但我认为有更好的解决方案):

    from unittest.mock import patch
    
    from django.core.cache.backends.dummy import DummyCache
    from django.utils.module_loading import import_string
    
    
    def no_cache(module_str, cache_object_str='cache'):
        """ example usage: with no_cache('app.tasks', 'cache'): """
        module_ = import_string(module_str)
        return patch.object(module_, cache_object_str, DummyCache('mock', {}))
    

    灵感来自this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-09
      • 2011-09-26
      • 2011-12-19
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      相关资源
      最近更新 更多