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.
For convenience, Django offers different levels of cache granularity: You can cache the output of specific views, you can cache only the pieces that are difficult to produce, or you can cache your entire site. Django also works well with “downstream” caches, such as Squid and browser-based caches.
Django relies on the cache backend to be thread-safe, and a single instance of a memcache. Client is not thread-safe. The issue is with Django only creating a single instance that is shared between all threads (django. core.
Django has a default caching system in the form of local-memory caching. It is very powerful and robust. This system can handle multi-threaded processes and is efficient. It is best for those projects which cannot use Memcached framework.
To use cache in Django, first thing to do is to set up where the cache will stay. The cache framework offers different possibilities - cache can be saved in database, on file system or directly in memory. Setting is done in the settings.py file of your project.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With