How to cache Django Rest Framework API calls?

前端 未结 2 1900
天涯浪人
天涯浪人 2020-12-07 17:02

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          


        
2条回答
  •  既然无缘
    2020-12-07 18:03

    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)
    

提交回复
热议问题