Caching websites with Django and Memcached...
... memcached installation, django configuration and how to use it for your website
After Caching web sites and web applications and When to use caching for web sites its time for a little sample. This sample shows the usage of Memcached for server-side application cache. The installation part is taken from my Ubuntu so it may differ depending from your OS/distribution.
What is Memcached: Memcached is a tool that allows you to store key-value pairs in you memory. The keys are limited to 250 Bytes and for better performance the value size is limited to 1MB(more details) but this size is fair enough for web usage.
Memcached installation:
apt-get install memcached
apt-get install python-memcache
CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
from django.core.cache import cache
def heavy_view(request):
cache_key = 'my_heavy_view_cache_key'
cache_time = 1800 # time to live in seconds
result = cache.get(cache_key)
if not result:
result = # some calculations here
cache.set(cache_key, result, cache_time)
return result
{% load cache %}
... non cached content here ...
{% cache 1800 latest_news %}
... here are latest news - cached ...
{% endcache %}
{% load cache %}
{% cache 300 recent_conversations request.user.id %}
... current user recent conversations - cached ...
{% endcache %}
Final words: as you see from the examples above using Django and Memcached is really easy. Using it correctly will speed up your website and respectively improve your user experience(UX) and SEO. Using it wrong will provide negative results. Just take a moment and think what can be cached, how long can it be cached and is there a reason to be cached. Try to avoid double caching - there is no need to use caching in templates and then cache the rendered template in the view too.