Heim > Fragen und Antworten > Hauptteil
Wenn Sie das mit Django gelieferte Modul verwenden, um den Redis-Cache zu verwalten, lautet der festgelegte Schlüssel beispielsweise „banners“. Wenn Sie den Namen in der Redis-CLI sehen, wird er zu „:1:banners“. von Django? Was ist mit Redis?
from django.core.cache import cache
def get_queryset(self):
key = "banners"
queryset = cache.get(key)
if not queryset:
queryset = Banner.objects.filter(valid=True)
cache.set(key, queryset, 3600)
return queryset
过去多啦不再A梦2017-06-10 09:50:11
这个是django cache的机制, key由前缀,版本号,真正的key组成。django在升级或者代码重构的时候有用,可以判断key是那个版本号,从而进行兼容(其它欢迎补充)
1.首先看django redis client api的实现:
# https://github.com/niwinz/django-redis/blob/master/django_redis/client/default.py
def get(self, key, default=None, version=None, client=None):
"""
Retrieve a value from the cache.
Returns decoded value if key is found, the default if not.
"""
if client is None:
client = self.get_client(write=False)
key = self.make_key(key, version=version)
try:
value = client.get(key)
except _main_exceptions as e:
raise ConnectionInterrupted(connection=client, parent=e)
if value is None:
return default
return self.decode(value)
... 中间省略代码 ...
def make_key(self, key, version=None, prefix=None):
if isinstance(key, CacheKey):
return key
if prefix is None:
prefix = self._backend.key_prefix
if version is None:
version = self._backend.version
return CacheKey(self._backend.key_func(key, prefix, version))
它使用了make_key这个函数制作新的key,至于真正的key是从_backend.key_func来的。
2.其次查看django cache backend实现
# https://github.com/django/django/blob/master/django/core/cache/backends/base.py
def default_key_func(key, key_prefix, version):
"""
Default function to generate keys.
Constructs the key used by all other methods. By default it prepends
the `key_prefix'. KEY_FUNCTION can be used to specify an alternate
function with custom key making behavior.
"""
return '%s:%s:%s' % (key_prefix, version, key)
def get_key_func(key_func):
"""
Function to decide which key function to use.
Defaults to ``default_key_func``.
"""
if key_func is not None:
if callable(key_func):
return key_func
else:
return import_string(key_func)
return default_key_func
class BaseCache(object):
def __init__(self, params):
... 中间省略代码 ...
self.key_prefix = params.get('KEY_PREFIX', '')
self.version = params.get('VERSION', 1)
self.key_func = get_key_func(params.get('KEY_FUNCTION'))
由此可见,django redis cache的key是有前缀,版本号,真正的key组成。