Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
Django

Python Memcached Implementation for Django Project

2022-07-19

A fundamental trade-off in dynamic websites is they’re dynamic. Every time a user requests a page, the Web server fetches data from database then applies logic and renders in templates.  This will affect page load time due to time taken by server to fetch data and apply the business logic,

That’s where caching comes in.

To cache something is to save the result of an expensive calculation so that you don’t have to perform the calculation next time. In This Blog Post, Lets see how to use Memcached for server-side application caching.  Memcached is an in-memory key-value pair store, that helps in caching dynamic websites. Django uses python-memcached binding for communication between our web application and Memcached Server. 

apt-get install memcached         #to install memcached-server
pip install python-memcached
Add the following settings to settings.py or django settings

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': 'unix:/tmp/memcached.sock',
    }
}

Now you're all set use caching.

from django.core.cache import cache
cache.set(cache_key, result, cache_time)          # to cache a value
cache.set_many({'a': 1, 'b': 2, 'c': 3})          # to cache many keys
cache.get(cache_key)                              # to retive a key from cache
cache.get_many(['a', 'b', 'c'])                   # to retrive many keys from cache

To use as Decorator:

from django.views.decorators.cache import cache_page

@cache_page(60 * 10)
def my_view(request):
    ....

the above code will cache the page for 10 mins.

For template level caching:

{% load cache %}
 ... non cached content here ...
{% cache  cache_key %}
cached content here
​{% endcache %}

If you want to delete a specific key from cache or clear entire cache.

cache.delete('a')     # where a is key
cache.delete_many(['a', 'b', 'c'])
cache.clear()

These are various forms of caching implementations.