Django Page Cache
July 1, 2011
This entry covers how to enable page level caching in Django. We'll be using a dummy cache backend for development, and the file based store for production. Memcached would be faster, but I'm on a memory limited VPS.
settings_common.py
In have a common settings file that is shared between production and development. For this, I added the following three cache settings:
CACHE_MIDDLEWARE_ALIAS = 'progperc' CACHE_MIDDLEWARE_SECONDS = 60 * 15 # 15 minute cache CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True
CACHE_MIDDLEWARE_ALIAS
sets the key to use for the site in the cache. CACHE_MIDDLEWARE_SECONDS
defines how long to cache for. CACHE_MIDDLEWARE_ANONYMOUS_ONLY
means that only anonymous users are served pages from the cache. Logged in users will bypass the cache, which is what we want - they will have dynamic features on the page tailored to their user.
Middleware classes also needs changing to add UpdateCacheMiddleware and FetchCacheMiddleware. I ended up with the following list:
MIDDLEWARE_CLASSES = ( 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.transaction.TransactionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.doc.XViewMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', )
settings_dev.py
In development, we set the cache to use a dummy back end.
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }
}
The above setting is for Django 1.3. For Django 1.2 use:
CACHE_BACKEND = 'dummy://'
settings_live.py
In production, we set the cache to use a directory on disk. This directory needs to be writable by the user that is running the web server.
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/site_cache', } }
The above setting is for Django 1.3. For Django 1.2 use:
CACHE_BACKEND = 'file:///var/site_cache'