comment 0

Install memcached in Django project

I put picture to make it interesting.

What is memcached ?

Free & open source, high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.

Memcached is simple yet powerful. Its simple design promotes quick deployment, ease of development, and solves many problems facing large data caches. Its API is available for most popular languages.

I can said that this is one of basic optimization when we develop an API or on situation where we need to consume API but with limit. Even though we can try to optimize the django ORM first, I barely suggest to implement this memcached for “first impression”.

Basically, Django support several memcached, the most famous are MemcachedCache and PyLibMCCache . I prefer the second one ( PyLibMCCache) because it’s written in C.

Preparation

Install the dependencies

sudo apt-get install memcached

or if you’re using docker, you can pull this image

  cache:
    image: memcached:latest
    ports:
      - "11211:11211"
    command:
    - '-m 128'

install the python library,

pip install python-memcached

if you want to using ‘django.core.cache.backends.memcached.MemcachedCache’ in your django, or

pip install pylibmc

for ‘django.core.cache.backends.memcached.MemcachedCache’

the next step is add cache configuration on your django project settings

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
        'LOCATION': 'cache:11211',
    }
}

in this example, I am using PyLibMCCache as my cache’s backend, and also docker, that’s why my chace location in cache with port 11211, if you’re not running on docker, just change it with localhost or 127.0.0.1 .

Since we deal with API, this is the example how to use cache on view’s class.

from django.core.cache import cache #import the cache from django core

CACHE_TIME = 300 # means remove the cache after 5 minutes

@api_view(['GET'])
@permission_classes((BasicPermission,))
@json_response
def movie_list(request):
    # set the cache key, dont use special character
    cache_key = "movie_list_key"
    # check if we have this data on our cache server
    data = cache.get(cache_key)
    if data is None:
        # if we doesnt have data, so get the data 
        movies = Movies.objects.all()
        data = {'total_movie':movies.count()}
        # save the data to cache
        cache.set(cache_key, data, CACHE_TIME)
    return data

happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *


 

This site uses Akismet to reduce spam. Learn how your comment data is processed.