How to use 2 different cache backends in Django?
I need to use memcached and file based cache. I setup my cache in settings:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': 'c:/foo/bar',
},
'inmem': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
dummy is temporary. Docs says:
cache.set('my_key', 'hello, world!', 30)
cache.get('my_key')
OK, but how can I now set and get cache o开发者_如何学编程nly for 'inmem' cache backend (in future memcached)? Documentation doesn't mention how to do that.
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': 'c:/foo/bar',
},
'inmem': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
from django.core.cache import get_cache, cache
inmem_cache = get_cache('inmem')
default_cache = get_cache('default')
# default_cache == cache
Since Django 1.9, get_cache
is deprecated. Do the following to address keys from 'inmem' (addition to answer by Romans):
from django.core.cache import caches
caches['inmem'].get(key)
In addition to Romans's answer above... You can also conditionally import a cache by name, and use the default (or any other cache) if the requested doesn't exist.
from django.core.cache import cache as default_cache, get_cache
from django.core.cache.backends.base import InvalidCacheBackendError
try:
cache = get_cache('foo-cache')
except InvalidCacheBackendError:
cache = default_cache
cache.get('foo')
From the docs:
>>> from django.core.cache import caches
>>> cache1 = caches['myalias']
>>> cache2 = caches['myalias']
>>> cache1 is cache2
True
Create a utility function called get_cache. The get_cache method referenced in other answers doens't exists in the django.core.cache library in some django versions. Use the following insteaed
from django.utils.connection import ConnectionProxy
from django.core.cache import caches
def get_cache(alias):
return ConnectionProxy(caches, alias)
cache = get_cache('infile')
value = cache.get(key)
Unfortunately, you can't change which cache alias is used for the low-level cache.set()
and cache.get()
methods.
These methods always use 'default' cache as per line 51 (in Django 1.3) of django.core.cache.__init__.py
:
DEFAULT_CACHE_ALIAS = 'default'
So you need to set your 'default' cache to the cache you want to use for the low-level cache and then use the other aliases for things like site cache, page cache, and db cache routing. `
精彩评论