The correct way to cache responses in django rest system

I am aware of https://github.com/chibisov/drf-extensions, but the assembly failed.

How should responses be cached for general views? For instance:

class PropertyList(generics.ListAPIView):

    queryset = Property.objects.all().prefetch_related("photos")
    serializer_class = PropertyListSerializer


    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('featured', 'state', 'price_cents','location', 'status')
    ordering_fields = ('expiration_date',)

Is the implementation of the list method from ListModelMixin the only option?

+5
source share
1 answer

There are several solutions for this:

  • You can use Cache for APIview and ViewSets with decorators such as cache_pageor vary_on_cookie. as below:

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

    For more on this, read the rest of the original caching page in Django.

  • -. , , django, cache.set. , , cache.set(cache_key, result, expire_time) , . , , , .

    fooobar.com/questions/503089/...

, - . . - , redis memcached ... .

0

Source: https://habr.com/ru/post/1651904/


All Articles