[Answered ]-Caching must be implemented at view level, in models or in serializers in Django

1👍

You can use Cache for APIview and ViewSets with decorators like cache_page.

NOTE: The cache_page decorator only caches the GET and HEAD responses with status 200.

Ex:

from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page

class UserViewSet(viewsets.ViewSet):
    # Cache requested url for each user for 2 hours
    @method_decorator(cache_page(60*60*2))
    def list(self, request, format=None):
        content = {
            'user_feed': request.user.get_user_feed()
        }
        return Response(content)

Or

class PostView(APIView):

    # Cache page for the requested url
    @method_decorator(cache_page(60*60*2))
    def get(self, request, format=None):
        content = {
            'title': 'Post title',
            'body': 'Post content'
        }
        return Response(content)

DRF cache docs.

settings.py:

# Enable memcache
# https://devcenter.heroku.com/articles/memcache#using_memcache_from_python
CACHES = {
    'default': {
        'BACKEND': 'django_pylibmc.memcached.PyLibMCCache'
    }
}

If you want store just result of a method or a query and store for furture requests, you can just define a key for it and set that result to that key with cache.set(cache_key, result, expire_time) and then get it(cache.get(cache_key)) whenever you want.
Remember you should define a cache backend for your results.Proper and better solution is to use message brokers like redis or memcached to store cache.based on your needs.

//Updated//

check if data is already cashed or not.

    class WeatherView(APIView):
        def get(self):
            if(cache.get('weatherdata') == None):
                url = 'https://api.openweathermap.org/data/2.5/forecast?q=' + '...';
                serialized_data = urlopen(url).read()
                data = json.loads(serialized_data)
                print(data)
    
                cache.set('weatherdata', data, 3600)
            else:
                data = cache.get('weatherdata')
    
            serializer_class = WeatherSerializer(data)
    
            responseJSON = JSONRenderer().render(serializer_class.data)
    
            return Response(responseJSON)

Leave a comment