sql >> Base de Datos >  >> NoSQL >> Redis

Django, Redis:dónde poner el código de conexión

Agregue esta línea al archivo de configuración para crear la conexión,

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

Caché de nivel de vista, almacenará en caché la respuesta de la consulta (datos)

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)

Caché de nivel de plantilla,

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()
     })

Para cualquier duda consulta este enlace

  1. ¿Cómo almacenar en caché las llamadas a la API de Django Rest Framework?
  2. https://github.com/realpython/django-redis-cache
  3. https://boostlog.io/@nixus89896/setup-caching-in-django-with-redis-5abb7d060814730093a2eebe