37
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
27
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)
- [Django]-How to use Django's assertJSONEqual to verify response of view returning JsonResponse
- [Django]-Query datetime by today's date in Django
- [Django]-Django.db.utils.OperationalError: fe_sendauth: no password supplied
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')
- [Django]-Why does django's prefetch_related() only work with all() and not filter()?
- [Django]-Django: How to build a custom form widget?
- [Django]-How to define two fields "unique" as couple
2
>>> from django.core.cache import caches
>>> cache1 = caches['myalias']
>>> cache2 = caches['myalias']
>>> cache1 is cache2
True
- [Django]-Django – No such table: main.auth_user__old
- [Django]-Running Scrapy spiders in a Celery task
- [Django]-How can django debug toolbar be set to work for just some users?
0
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)
- [Django]-Django or Django Rest Framework
- [Django]-Django: multiple models in one template using forms
- [Django]-Django best approach for creating multiple type users
-2
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.
`
- [Django]-How to query directly the table created by Django for a ManyToMany relation?
- [Django]-Django 1.7 upgrade error: AppRegistryNotReady: Apps aren't loaded yet
- [Django]-How to use Cassandra in Django framework