Django缓存不会刷新 [英] Django cache does not get refreshed

查看:612
本文介绍了Django缓存不会刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的Web应用程序中添加了一个简单的缓存,当我删除或添加新对象时,缓存在我设置的时间(2分钟)之后不会刷新。



它似乎冻结了。当我重新启动应用程序时,它会被刷新。



我在memached和locmemcache上尝试过。

  INDEX_LIST_CACHE_KEY =index_list_cache_key

class IndexView(BaseView):
queryset = Advert.objects.all()。select_related('category','location')
template_name =adverts / category_view.html

def get_queryset(self):
queryset = cache.get(INDEX_LIST_CACHE_KEY)
如果查询是没有:
queryset = self.queryset
cache.set(INDEX_LIST_CACHE_KEY,queryset,2 * 60)
返回查询

为什么缓存在这个项目中的行为是如此?



编辑 - settings.py:



for locmemcache

  CACHES = {
'default':{
' BACKEND':'django.core.cache.backends.locmem.LocMemCache',
'LOCATION':'oglos-cache'
}
}

for memcached

 code> CACHES = {
'default':{
'BACKEND':'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION':'127.0。 0.1:11211',
}
}


解决方案>

因为通过在类定义中切片查询器,所以您已经在类定义时刻(即服务器启动时)对它进行了评估。因此,缓存正在刷新,但只能使用一组旧的项目。不要在类级别做这个切片:从 get_queryset 返回结果时执行此操作。


I've added a simple caching to my web application and when I delete or add new object the cache does not get refreshed after the peroid of time (2 minutes) that I've set.

It looks like it froze. When I restart my application then it gets refreshed.

I tried it on memached and locmemcache.

INDEX_LIST_CACHE_KEY = "index_list_cache_key"

class IndexView(BaseView):
    queryset = Advert.objects.all().select_related('category', 'location')[:25]
    template_name = "adverts/category_view.html"

    def get_queryset(self):
        queryset = cache.get(INDEX_LIST_CACHE_KEY)
        if queryset is None:
            queryset = self.queryset
            cache.set(INDEX_LIST_CACHE_KEY, queryset, 2 * 60)
        return queryset

Why caching behaves like that in this project?

Edit - settings.py:

for locmemcache

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'oglos-cache'
    }
}

for memcached

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

解决方案

Because by slicing the queryset in the class definition, you've evaluated it then and there - at class definition time, ie when the server starts up. So the cache is being refreshed, but only with an old set of items. Don't do that slice at class level: do it when returning the results from get_queryset.

这篇关于Django缓存不会刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆