Django缓存cache.set不存储数据

问题描述 投票:0回答:3

当我运行

python manage.py shell
然后:

from django.core.cache import cache
cache.set("stack","overflow",3000)
print cache.get("stack")

(output: ) None

我尝试重新启动内存缓存,这是我的设置:

CACHES = { 
  'default' : { 
     'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 
     'LOCATION' : '127.0.0.1:11211',
  }
}
django caching memcached
3个回答
3
投票

确保它使用正确的缓存。尝试

from django.core.cache import caches
,然后查看
caches.all()
的内容。它应该只有一个
django.core.cache.backends.memcached.MemcachedCache
实例。
如果是,请尝试直接访问它,例如

from django.core.cache import caches  
m_cache = caches.all()[0]
m_cache.set("stack","overflow",3000)
m_cache.get("stack")

这可能无法解决您的问题,但至少会让您更接近调试 Memcached,而不是 Django 的缓存代理或您的配置。


0
投票

我相信 django 通过版本增强了密钥。例如,

django_memcache.set('my_key', 'django', 1000)

将在内存缓存中设置密钥

:1:my_key

<36 set :1:my_key 0 1000 6
>36 STORED

但是,如果您通过 telnet 或 python-memcached 模块设置密钥,它将按预期存储原始密钥:

<38 set my_key 0 1000 13 
>38 STORED

那么,也许您没有查询正确的密钥?

参见https://docs.djangoproject.com/en/1.10/topics/cache/#cache-key-transformation


0
投票

我可以设置并获取默认使用的LocMemCache,如下所示。 *get_many()可以获取多个值,get_or_set()可以在键存在时获取键的值,如果键不存在则设置并获取键的值:

from django.core.cache import cache

def test(request):
    cache.set("name", "John")
    cache.set("age", 36)
    print(cache.get("name")) # John
    print(cache.get("age")) # 36
    print(cache.get_many(["name", "age"])) # {'name': 'John', 'age': 36}
    print(cache.get_or_set("gender", "Male")) # Male
    return HttpResponse("Test")
© www.soinside.com 2019 - 2024. All rights reserved.