Django redis缓存重建

时间:2018-01-26 21:43:57

标签: python django redis

我们有一个应用程序,需要在缓存中更新每日数据。因此,如果我们清除数据是否有任何简单的方法来重建缓存而无需访问所有页面和组合。有没有办法自动化。

1 个答案:

答案 0 :(得分:0)

我为来自" sql-lite"的时间缓存数据创建装饰器类与Django模型:
这种方法对你有帮助吗?

装饰:

class MWT(object):
    """Memoize With Timeout CACHE as a decorator"""
    _caches = {}
    _timeouts = {}

    def __init__(self, timeout=2):
        self.timeout = timeout

    def collect(self):
        """Clear cache of results which have timed out"""
        for func in self._caches:
            cache = {}
            for key in self._caches[func]:
                if (time.time() - self._caches[func][key][1]) < self._timeouts[func]:
                    cache[key] = self._caches[func][key]
            self._caches[func] = cache

    def __call__(self, f):
        self.cache = self._caches[f] = {}
        self._timeouts[f] = self.timeout

        def func(*args, **kwargs):
            kw = kwargs.items()
            kw.sort()
            key = (args, tuple(kw))
            try:
                v = self.cache[key]
                if (time.time() - v[1]) > self.timeout:
                    raise KeyError
            except KeyError:
                v = self.cache[key] = f(*args, **kwargs), time.time()
            return v[0]

        func.func_name = f.func_name

        return func

我的模特:

class MySimpleModel(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return "{} - {}".format(self.name, self.id)

    def __set__(self):
        return self.name

然后我使用这个方法(定义装饰器)来阅读Django模型:

class SQLData(object):
    def __init__(self, name):
        self._name = name

    def name(self):
        return self._name


@MWT(timeout=10)  # You can set any value to timeout (time of clearing cache).
def sql_reader():
    return list(MySimpleModel.objects.all())  # Using list method as faster to read sql.

class GetData(object):
    def __init__(self): 
        pass

    @classmethod
    def get_data(cls):
        result = []

        for data in sql_reader():
            data = SQLData(data.name)
            result.append(data)

        return result