'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 only for 'inmem' cache backend (in future memcached)? Documentation doesn't mention how to do that.
Solution 1:[1]
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
Solution 2:[2]
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)
Solution 3:[3]
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')
Solution 4:[4]
>>> from django.core.cache import caches
>>> cache1 = caches['myalias']
>>> cache2 = caches['myalias']
>>> cache1 is cache2
True
Solution 5:[5]
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)
Solution 6:[6]
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. `
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Romans |
| Solution 2 | nichoio |
| Solution 3 | Tomatohater |
| Solution 4 | Neil |
| Solution 5 | Jassim Abdul Latheef |
| Solution 6 | Van Gale |
