I have to query redis on every request in my Django-app. Where can I put the setup/ connection routine (r = redis.Redis(host='localhost', port=6379)
) so that I can access and reuse the connection without having to instantiate a new connection in my views?
Asked
Active
Viewed 901 times
-1

F.M.F.
- 1,929
- 3
- 23
- 42
-
Create a connection in django settings file. If you had any doubts refer here https://niwinz.github.io/django-redis/latest/ – Sakthi Panneerselvam Feb 05 '19 at 12:46
-
I don't see where they are creating the connection at the provided link – F.M.F. Feb 05 '19 at 12:51
-
scroll down and check it in the User Guide topic https://niwinz.github.io/django-redis/latest/#_user_guide – Sakthi Panneerselvam Feb 05 '19 at 12:55
-
this does not instantiate the connection – F.M.F. Feb 05 '19 at 13:03
-
It will work, i don't know why it's not working for you. One more time read the doc properly – Sakthi Panneerselvam Feb 05 '19 at 13:15
-
How can I access the connection in my views then? – F.M.F. Feb 05 '19 at 14:07
-
Please give me a reason for downvoting so that I can improve my question-quality. – F.M.F. Feb 05 '19 at 14:08
1 Answers
2
Add this line to Settings file for creating connection,
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient"
},
"KEY_PREFIX": "example"
}
}
# Cache time to live is 15 minutes.
CACHE_TTL = 60 * 15
View level Cache, It will cache the query response(data)
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
class TestApiView(generics.ListAPIView):
serializer_class = TestSerializer
@method_decorator(cache_page(60))
def dispatch(self, *args, **kwargs):
return super(TestApiView, self).dispatch(*args, **kwargs)
Template level cache,
from django.conf import settings
from django.core.cache.backends.base import DEFAULT_TIMEOUT
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from .services import get_recipes_with_cache as get_recipes
CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)
@cache_page(CACHE_TTL)
def recipes_view(request):
return render(request, 'index.html', {
'recipes': get_recipes()
})
For any doubts refer this links

Sakthi Panneerselvam
- 1,337
- 1
- 14
- 25