使用django自帶的模組處理redis快取時,設定好的key比如說時“banners”, 到了在redis的cli下看到name就變成了“:1:banners”,這是django的機制,還是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組成。