How to cache Django Rest Framework API calls?

前端 未结 2 1899
天涯浪人
天涯浪人 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)
    
    0 讨论(0)
  • 2020-12-07 18:07

    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)
    
    0 讨论(0)
提交回复
热议问题