Django - Using Memcached
The easiest way to use Memcached as a cache backend for django is to enable it to cache the entire site:
1. Install Memcached:
$ sudo apt-get install memcached
The memcached service will run at 127.0.0.1:11211 by default.
2. Install python API for memcached:
(myvirtualenv)$ pip install python-memcached
3. Enable Django to use Memcached by modified settings.py:
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware', # should be the first line
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware', # should be the last line
)
#memcache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 60
CACHE_MIDDLEWARE_KEY_PREFIX = 'mydjangoapp'
4. If you want to verify whether Memcached works:
$ sudo service memcached stop
$ memcached -vv
try to access the django site and see the Memcached outputs in the terminal
References: https://docs.djangoproject.com/en/1.6/topics/cache/
1. Install Memcached:
$ sudo apt-get install memcached
The memcached service will run at 127.0.0.1:11211 by default.
2. Install python API for memcached:
(myvirtualenv)$ pip install python-memcached
3. Enable Django to use Memcached by modified settings.py:
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware', # should be the first line
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware', # should be the last line
)
#memcache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 60
CACHE_MIDDLEWARE_KEY_PREFIX = 'mydjangoapp'
4. If you want to verify whether Memcached works:
$ sudo service memcached stop
$ memcached -vv
try to access the django site and see the Memcached outputs in the terminal
References: https://docs.djangoproject.com/en/1.6/topics/cache/
Comments
Post a Comment