How to cache Django Rest Framework API calls? How to cache Django Rest Framework API calls? django django

How to cache Django Rest Framework API calls?


Ok, so, in order to use caching for your queryset:

class ProductListAPIView(generics.ListAPIView):    def get_queryset(self):        return get_myobj()    serializer_class = ProductSerializer

You'd probably want to set a timeout on the cache set though (like 60 seconds):

cache.set(cache_key, result, 60)

If you want to cache the whole view:

from django.utils.decorators import method_decoratorfrom django.views.decorators.cache import cache_pageclass ProductListAPIView(generics.ListAPIView):    serializer_class = ProductSerializer    @method_decorator(cache_page(60))    def dispatch(self, *args, **kwargs):        return super(ProductListAPIView, self).dispatch(*args, **kwargs)


I just implemented this to use on my serializers

def cache_me(cache):    def true_decorator(f):        @wraps(f)        def wrapper(*args, **kwargs):            instance = args[1]            cache_key = '%s.%s' % (instance.facility, instance.id)            logger.debug('%s cache_key: %s' % (cache, cache_key))            try:                data = caches[cache].get(cache_key)                if data is not None:                    return data            except:                pass            logger.info('did not cache')            data = f(*args, **kwargs)            try:                caches[cache].set(cache_key, data)            except:                pass            return data        return wrapper    return true_decorator

then i override the to_representation method on my serializers, so it caches the serialized output per instance.

class MyModelSerializer(serializers.ModelSerializer):    class Meta:        model = MyModel        exclude = ('is_deleted', 'facility',)    @cache_me('mymodel')    def to_representation(self, instance):       return super(MyModelSerializer, self).to_representation(instance)