As with most frameworks, the Django framework for Python can make use of caching to greatly improve performance for many common requests. Here we will look at using memcached as it enjoys good Django support and production use although there is also Redis support which definitely improves on memcached in some aspects such as data persistence.
- The first step is to install memcached on your server:
- Let Django know how to access memcached:
- Load the cache within your application
- Save the value to the cache
- Retrieve the value from the cache
yum install memcached
Ubuntu / Debian Linux:
apt-get install memcached
settings.py file, add the following line:
from django.core.cache import cache
exampleValue = cache.get('exampleValue')
The beauty being that
exampleValue can be anything from a computed / database retrieved value to large blocks of static text or a URL etc.
The only problem with caches is they don’t always contain the data you expect, what if the value got flushed or hasn’t yet been stored? Lets rewrite step 5 to handle the event of the value not being available in the cache:
exampleValue = cache.get('exampleValue') if not exampleValue: exampleValue = exampleValueLookup cache.set('exampleValue',exampleValue)
Here we see the value
exampleValue being retrieved with a backup regeneration if the value has not been set. In a real application this would usually be encapsulated in a
getExampleValue function or somewhere appropriate.