39

I'm using Memcached as backend to my django app. This code works fine in normal django query:

def get_myobj():
        cache_key = 'mykey'
        result = cache.get(cache_key, None)
        if not result:
            result = Product.objects.all().filter(draft=False)
            cache.set(cache_key, result)
        return result

But it doesn't work when used with django-rest-framework api calls:

class ProductListAPIView(generics.ListAPIView):
    def get_queryset(self):
        product_list = Product.objects.all()
        return product_list
    serializer_class = ProductSerializer

I'm about to try DRF-extensions which provide caching functionality:

https://github.com/chibisov/drf-extensions

but the build status on github is currently saying "build failing".

My app is very read-heavy on api calls. Is there a way to cache these calls?

Thank you.

Kitti Wateesatogkij
  • 979
  • 2
  • 12
  • 23
  • Did you decorate the method with "@cache_response()" ? – Priyank Kapadia Jul 12 '16 at 04:40
  • Hi. @cache_response is from DRF-extensions which I haven't try implementing it yet because the build status says "build failing" on their github page : https://github.com/chibisov/drf-extensions – Kitti Wateesatogkij Jul 12 '16 at 05:04
  • 1
    You realize that the view you pasted doesn't call the cache ? – Linovia Jul 12 '16 at 06:44
  • Yes I modify values in admin and reload the drf web-browsable api. Values always changed after refresh. Default timeout should be 5 mins if my memory serves – Kitti Wateesatogkij Jul 12 '16 at 07:11
  • But product list on website does not change if refreshed within 5 mins interval. So I assume the cache is working(for website) – Kitti Wateesatogkij Jul 12 '16 at 07:15
  • ok, so now, what's the question here ? Are you asking why it doesn't work or how should you make it work ? – Linovia Jul 12 '16 at 08:37
  • Hi, The question is how to cache the django-rest-framework api calls. Most of my users are using Android app, not the website. The app make lots of api calls to request the product list, which DRF returns .json. I want to cache this .json response so my Postgres DB won't be hit every time user request a product list. ;) – Kitti Wateesatogkij Jul 12 '16 at 09:31
  • Oh sorry. I just realize that you maybe talking about drf-extension. Let's not use that because its status is ' build-failing' ;) – Kitti Wateesatogkij Jul 12 '16 at 09:39

2 Answers2

58

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_decorator
from django.views.decorators.cache import cache_page

class ProductListAPIView(generics.ListAPIView):
    serializer_class = ProductSerializer

    @method_decorator(cache_page(60))
    def dispatch(self, *args, **kwargs):
        return super(ProductListAPIView, self).dispatch(*args, **kwargs)
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
Linovia
  • 19,812
  • 4
  • 47
  • 48
3

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)
Marco Silva
  • 639
  • 7
  • 8