Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

python - Django, Redis: Where to put connection-code

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  1. How to cache Django Rest Framework API calls?
  2. https://github.com/realpython/django-redis-cache
  3. https://boostlog.io/@nixus89896/setup-caching-in-django-with-redis-5abb7d060814730093a2eebe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...