Django caching with Redis

Question:

I have implemented django caching using redis following this blog: https://realpython.com/caching-in-django-with-redis/

So I followed this, installed the package,
Added in

CACHES = {
"default": {
    "BACKEND": "redis_cache.RedisCache",
    "LOCATION": "redis://127.0.0.1:8000/",
    "OPTIONS": {
        "CLIENT_CLASS": "django_redis.client.DefaultClient"
    },
    "KEY_PREFIX": "example"
}

}

Then in views.

from django.conf import settings
from django.core.cache.backends.base import DEFAULT_TIMEOUT
from django.views.decorators.cache import cache_page

CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)

and then added the decorator for the function

@cache_page(CACHE_TTL)
@login_required_dietitian
def patient_profile(request, id):
    data = {}
    return render(request, 'profile.html', {'data':data})

And then I am getting this error while I run the server

redis.exceptions.ConnectionError: Connection closed by server.

I am new to such caching technique, Any suggestion how to resolve this issue?

Asked By: Harshit verma

||

Answers:

Your configuration specifies Redis on port 8000, Redis, by default, runs on port 6379. Looks like its trying to connect your Django app, hence the Connection Error. Redis runs as a separate process, listening for requests on port 6379.

Answered By: Mark Barrett

First of all follow this https://computingforgeeks.com/how-to-install-redis-on-fedora/ guide to install redis into your system and start it. In my case it is fedora and there is a link to Ubuntu on the page.

Change the port from 8000 to 6379 on LOCATION. Now then you’ll be up and running.

I’d encourage this for a tutorial on redis for caching

Answered By: Boy Nandi