9

I've seen all over problems using Memcached in Django projects which is considered to be

The fastest, most efficient type of cache supported natively by Django

For instances,

So, how can we then use it?

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
  • The django.core.cache.backends.memcached.MemcachedCache backend is deprecated as python-memcached has some problems and seems to be unmaintained. Use django.core.cache.backends.memcached.PyMemcacheCache or django.core.cache.backends.memcached.PyLibMCCache instead. – Chandragupta Borkotoky Dec 03 '22 at 05:32

1 Answers1

11

This answer explains how to install Memcached on Windows 10 and how to integrate it with Django through a specific client. It was validated using Memcached 1.4.4, Python 2.7 and Django 1.11.

  1. In your Django project, under settings.py, add the following code in the bottom of the file

    SESSIONS_ENGINE='django.contrib.sessions.backends.cache'
    
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': '127.0.0.1:11211',
        }
    }
    
  2. Install memcached client for Python with your virtual environment active (python-memcached)

    pip install python-memcached
    
  3. Download Memcached using one of the following download links and extract it to a particular folder

This is the memcached folder in Windows

  1. Open that folder location in the Terminal or PowerShell and run

    .\memcached.exe -h
    

you should get something like this

memcached -help command

  1. Run the following command (-m is for the amount of memory you want to dedicate and -vvv is for extreme verbose)

    .\memcached.exe -m 512 -vvv
    

Memcache working fine

  1. In the view you want to use cache, specify it in urls.py like

    from django.conf.urls import include, url
    from django.views.decorators.cache import cache_page
    
    from .views import IndexView
    
    urlpatterns = [
        url(r'^$', cache_page(60*60)(IndexView.as_view()), name="index"),
    ]
    
  2. Go to the Django project, start the server and you should get much better results in your Time load.

Improve site performance with Memcached

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
  • Do you know if this approach is a "good" idea to implement in an AWS Elastic Beanstalk environment where auto-scaling may take place? I'd like to avoid paying for AWS Elasticache memcached until my app gains traction. – Jarad Sep 27 '21 at 21:53
  • 1
    @Jarad might be helpful to consider [this answer](https://stackoverflow.com/a/33359475/5675325) and [this one](https://stackoverflow.com/a/49322774/5675325) – Tiago Martins Peres Sep 28 '21 at 02:06