Django with Redis as Cache Backend and Session Storage

Adi Ramadhan
3 min readMay 18, 2024

--

Reference: https://www.djangoproject.com/ https://redis.io/
Redis is a source-available, in-memory storage, used as a distributed, in-memory key–value database, cache and message broker, with optional durability.
Storing cache and session in Redis can provide better performance.

Performance improvement with redis cache
Store and Flush session data

Prerequisite:
Redis server (localhost, heroku or other redis server) running

Step 1: Preparation, Create Django Project, Inital Migration
create virtualenv: virtualenv venv
start virtualenv: venv/Scripts/activate
install Django in virtualenv: pip install django==4.2 django-redis
Create Django: django-admin startproject myproject
Go to myproject folder: cd myproject
Initial Migration: python manage.py migrate

Step 2: Create Django App
Create apps: python manage.py startapp myapp

Step 3: Project Setting: Register Apps, Set Templates Folder, Redis Config (myproject/settings.py)

...

INSTALLED_APPS = [
...
'myapp', # updated
'django_redis', # django redis
]

...

TEMPLATES = [
...
'DIRS': [Path(BASE_DIR, 'templates')], #updated
...
]

...

# redis cache and session config
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://localhost:6379/0', # redis location
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default' # cache alias name

Step 4: Create HTML Files in Templates Folder

Create templates folder in main app

Create templates/cache.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
</head>
<body>
<h1>Index Homepage</h1>
<p>Request session example: {{request.session.some_example}}</p>
<a href="{% url 'add_session_data'%}">Add session data</a>
<a href="{% url 'clear_session_data'%}">Clear session data</a>
</body>
</html>

Create templates/session.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
</head>
<body>

<p>Data session example: {{my_session_data}}</p>
<a href="{% url 'add_session_data'%}">Add session data</a>
<a href="{% url 'clear_session_data'%}">Clear session data</a>

</body>
</html>

Step 5: Create Function Views myapp/views.py

from django.shortcuts import render, redirect
from django.core.cache import cache
import time

# Cache Store

def cache_test(request):
template = "cache.html"

start_time = time.time()
data = None #return data
use_cache = None

my_cache_data = cache.get('my_cache_data')

if my_cache_data:
use_cache = True
data = my_cache_data
else:
data = "some example data" # lookup from database or another source which is long running process
time.sleep(5) # long running process simulation
cache.set('my_cache_data', data, timeout=3600) # Cache for 1 hour
use_cache = False

duration = time.time() - start_time

extra_context = {
"data": data,
"duration": duration,
"use_cache": use_cache,
}
return render(request, template, extra_context)

def clear_cache_data(request):
cache.clear() # clear session data
return redirect("cache_test") #after clear, will redirect to cache test without cache stored


# Session Store

def session_test(request):
template = "session.html"
my_session_data = request.session.get("my_session_data")

extra_context = {
"my_session_data": my_session_data,
}
return render(request, template, extra_context)

def add_session_data(request):
request.session["my_session_data"] = "John Doe"
return redirect("session_test")

def clear_session_data(request):
request.session.flush() # clear session data
return redirect("session_test")

Step 8: Setup URLS

Create myapp/urls.py

from django.urls import path
from . import views

urlpatterns = [
path("cache_test", views.cache_test, name="cache_test"),
path("clear_cache_data", views.clear_cache_data, name="clear_cache_data"),

path("session_test", views.session_test, name="session_test"),
path("add_session_data", views.add_session_data, name="add_session_data"),
path("clear_session_data", views.clear_session_data, name="clear_session_data"),
]

Update myproject/urls.py

from django.contrib import admin
from django.urls import path, include #updated

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')), #updated
]

Step 9: Run Server and Testing
Run Server: python manage.py runserver
Testing:
http://127.0.0.1:8000/cache_test

Performance improvement with redis cache

http://127.0.0.1:8000/session_test

Store and Flush session data

Redis

Cache and session stored in redis

--

--

Adi Ramadhan
Adi Ramadhan

No responses yet