How to use Redis in Django to speed up your Django application
Hello fellow Python enthusiasts,
Today, I’m thrilled to delve into the dynamic duo of Redis and Django. If you’ve ever battled sluggish APIs, server hiccups, or those pesky 502 errors, you’re in for a treat.
You can find the full post right here. And if you’re curious about my professional journey, feel free to connect with me on LinkedIn or dive into the code on GitHub.
So, let’s chat about Redis.
Redis is like a finely-tuned race car in the world of storage systems. It doesn’t just store your data; it revs up its engines and keeps everything in cache for swift retrieval. Now, how does this relate to turbocharging Django’s performance? Buckle up; here’s the ride!
When you blend Redis with Django, you equip yourself with a secret weapon to combat slowdowns caused by a barrage of database queries. Here’s the magic: Redis acts as a data guardian, and you can access that data frequently without repeatedly knocking on the database’s door. The result? Reduced database strain and turbocharged API responses and Django queries.
Using Redis with Django: A Step-by-Step Guide
So, now we’ll learn how to use redis with django for optimization.
We’ll test redis with 10k+ objects.
So, first of all download Redis:-
Download Redis
Redis for 64-bit Windows from this GitHub page: https://github.com/MicrosoftArchive/redis/releases/download/win-3.0.504/Redis-x64-3.0.504.msi
and after installing this, Go to your installed directory and run the redis-cli
and now we start our django project, I hope you guys know how to create a django project and django app.
Now, add redis configuration in django settings.py
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1', # Replace with your Redis server details
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}
now create a model in models.py file,
class Post(models.Model):
title = models.CharField(max_length=250)
description = models.TextField()
def __str__(self):
return self.title
and add some objects and run script for adding duplicate data in the model, now we write main logic for the redis for set the cache and get the cache,
from django.shortcuts import render
from post.models import Post
from django.core.cache import cache
from django.http import HttpResponse
# Create your views here.def home(request):
qs = Post.objects.all()
context = {'qs':qs}
return render(request, 'index.html', context)def set_data_in_cache(request):
# Retrieve the data you want to cache
qs = Post.objects.all() # Set the data in the Redis cache
cache.set('post_data_key', qs) return HttpResponse("Data has been set in the cache.")def get_data_from_cache(request):
# Get the data from the Redis cache
cached_data = cache.get('post_data_key')
print(cached_data, 'cached_data') if cached_data is not None:
# If data is found in the cache, you can use it as needed
return render(request, 'redis_data.html', {'qs': cached_data})
else:
# If data is not found in the cache, you may choose to retrieve it from the database
qs = Post.objects.all()
return render(request, 'index.html', {'qs': qs})
we use two function for set and get the cache in redis, and that’s so simple and easy,
for set the cache we use:- cache.set('post_data_key')
`
for get the cache we use:- cache.get('post_data_key')
and we set the Post model data in redis cache key and then we fetch the data from the cache key which you set in redis, and there’s one more thing and that is timeout, if you want to expire your cache key so you can add the timeout while setting the cache key, you can use timeout=20 or any number, and if you don’t want to expire your key, then use timeout=None, so that’s how we can optimize our django app with the use of Redis.
Thank You
Shivam Rohilla | Python Developer