Mayank Jain
Mayank Jain

Reputation: 379

I wanna use Redis-Cache in my simple Django project. I'm not able to understand the implementation in Django

Here below, this is my view. Now in this, I'm not able to get the way to implement the Redis Cache.

from django.core.cache import cache class UserListView(APIView):

def get(self, request):

    # userss = Cach.objects.values('cache_id', 'username', 'email')
    data = Cach.objects.values('cache_id', 'username', 'email')

    # cache.set('users',userss)

    # data = cache.get('users')

    return Response(data)

Upvotes: 2

Views: 1244

Answers (2)

Benyamin Jafari
Benyamin Jafari

Reputation: 33986

In order to use Django Redis Cache, you need to the Redis and some configuration on Django and its APIView.

The following configuration should be placed in the Django project settings.py:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://redis:6379",
        "TIMEOUT": 5 * 60,
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient"
        },
        "KEY_PREFIX": "example"
    }
}

In order to set cache per all site view the following changes should be used in Django middleware in settings.py:

MIDDLEWARE = [
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
]

According to this doc all of the views will be cachable.


If you want to use the cache per each view you could use its relevant decorator in Django as follows:

from django.views.decorators.cache import cache_page

@cache_page(60 * 5)
def my_view(request):
    ...

In addition, if you are using the REST-API, you must be used with the following decorator instead (@method_decorator(cache_page(60 * 5))) doc. Here is an example:

from django.utils.decorators import method_decorator

class PostView(APIView):
    @method_decorator(cache_page(60 * 5))
    def get(self, request, format=None):
        content = {
            'title': 'Post title',
            'body': 'Post content'
        }
        return Response(content)

[NOTE]:

  • Requirement: pip install django-redis
  • In the above mentioned, the used Redis sevice is a dockerized container which its docker-compose.yml part is as follows:

      redis:
        restart: always
        image: redis:latest
        ports:
          - "6379:6379"
    

Thus, if you want to use a locally Redis, you must replace "LOCATION": "redis://redis:6379", with "LOCATION": "redis://127.0.0.1:6379",

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174624

The logic for implementing any cache is the following:

  1. Check if object exists in cache by fetching it.
  2. If it doesn't exist, calculate the object (or generate it) and put it in the cache.
  3. Return the object.

Django provides a simple dictionary-like API for caches. Once you have correctly configured the cache, you can use the simple cache api:

from django.core.cache import cache

def get(request):
   value = cache.get('somekey')
   if not value:
      # The value in the cache for the key 'somekey' has expired
      # or doesn't exist, so we generate the value
      value = 42
      cache.set('somekey', value)

There is a lot more to caching in django, make sure you read the documentation which describes how to use caching in templates, how to cache the entire view output and more.

Upvotes: 1

Related Questions