DEV Community

Gias Uddin
Gias Uddin

Posted on • Edited on

All you need to about Django Caching-redis-cache

Application performance tuning and decrease the load time of a web application is very important for successful products. Redis, a versatile tool, is an open-source, in-memory data structure store, used as a database, cache, and message broker. In this blog, I will show you how to use Redis for Django caching.

Let’s assume you have already created a Django project in your pc.

Install redis and django-redis

sudo apt-get install redis-server
pip install django-redis
Enter fullscreen mode Exit fullscreen mode

check redis in shell

$ redis-cli ping
output: PONG
Enter fullscreen mode Exit fullscreen mode

Now add cache configuration in your Django application settings.py

CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379/",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient"
            },
            "KEY_PREFIX": "testApp"
        }
    }
Enter fullscreen mode Exit fullscreen mode

_We have enabled cache backend but none of the view is enable for cache.
_

Now we will enable cache for django per view

@cache_page( 60 * 15, "blog" );
def blog( request ):
    ...............
    ...............
    response = render(request, 'template')

    return response
Enter fullscreen mode Exit fullscreen mode

Also, you can apply this decorator in urls.py, that is convenient for Class-Based Views or function base view:

from django.views.decorators.cache import cache_page

urlpatterns = [
    url(r'^$', cache_page(600)(BlogListView.as_view()), name='articles_list'),
    ...
]
Enter fullscreen mode Exit fullscreen mode

**
Template fragment caching**

{% load cache %}

<h1>Articles list</h1>

<p>Authors count: {{ authors_count }}</p>

<h2>Top authors</h2>

{% cache 500 top_author %}
<ul>
    {% for author in top_authors %}
    <li>{{ author.username }} ({{ author.articles_count }})</li>
    {% endfor %}
</ul>
{% endcache %}

{% cache 500 articles_list %}
{% for article in articles %}
<article>
    <h2>{{ article.title }}</h2>
    <time>{{ article.created_at }}</time>
    <p>Author: <a href="{% url 'author_page' username=article.author.username %}">{{ article.author.username }}</a></p>
    <p>Tags:
    {% for tag in article.tags.all %}
        {{ tag }}{% if not forloop.last %}, {% endif %}
    {% endfor %}
</article>
{% endfor %}
{% endcache %}

Enter fullscreen mode Exit fullscreen mode

If you need per user base separate caching then we can use this way

{% cache 500 personal_articles_list request.user.username %}
    <!-- ... -->
{% %}
Enter fullscreen mode Exit fullscreen mode

The low-level caching

from django.core.cache import cache

class AuthorListView(ListView):

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        authors_count = cache.get('authors_count')
        if authors_count is None:
            authors_count = Author.objects.count()
            cache.set('authors_count', authors_count)
        context['authors_count'] = authors_count
        ...
        return context
Enter fullscreen mode Exit fullscreen mode

cached_property decorator

class UserBio(models.Model):

    username = models.CharField(max_length=64, db_index=True)
    email = models.EmailField()
    bio = models.TextField()

    @cached_property
    def articles_count(self):
        return self.articles.count()
Enter fullscreen mode Exit fullscreen mode

Django cache clear

from django.core.cache import cache
# all cache delete
 cache.clear()
# specifiq cache delete by cache key
cache.delete('authors_count')
Enter fullscreen mode Exit fullscreen mode

Thank you for reading my article! If you enjoyed it and would like to support my work, please consider buying me a coffee at Buy Me a Coffee. You can also learn more about me and my work by visiting my Giasuddin Bio and following me on LinkedIn and Twitter. Thank you for your support!

Top comments (0)