Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to cache responses in django rest framework

I am aware of https://github.com/chibisov/drf-extensions but the build is failing.

How should responses be cached for generic views? For example:

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 implementing the list method from the ListModelMixin the only option?

like image 954
ajaxon Avatar asked Aug 20 '16 20:08

ajaxon


People also ask

Can REST responses be cached?

Caching in REST APIs POST requests are not cacheable by default but can be made cacheable if either an Expires header or a Cache-Control header with a directive, to explicitly allows caching, is added to the response. Responses to PUT and DELETE requests are not cacheable at all.

What are the caching strategies in Django?

To use cache in Django, first thing to do is to set up where the cache will stay. The cache framework offers different possibilities - cache can be saved in database, on file system or directly in memory. Setting is done in the settings.py file of your project.

Should you cache REST API?

The business reason to use caching is that it helps us gain speed, reduce server load, and reduce our dollars spent. A RESTful API being cacheable is one of the most important REST constraints and one of the most important ways of handling large scale.


1 Answers

There are some solutions for that:

  • You can use Cache for APIview and ViewSets with decorators like cache_page or vary_on_cookie. like 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)
    

    read More about it in Django rest original page for caching

  • You can also do it in your own way. I mean you can just use cache methods provided in django like cache.set. for example to store just result of a method or a query and store for furture requests, you can just define a key for it and set that result to that key with cache.set(cache_key, result, expire_time) and then get it whenever you want. So just if the cache was available for that key, then fetch else then again fetch result from database and store it again.

    By the way it's almost a duplicate of this link on stackoverflow

Remember you should define a cache backend for your results. by default you can use database backend to store results with keys on database or file system. But a proper and better solution is to use message brokers like redis or memcached or ... based on your needs.

here are some other useful links:

  • setting up the cache (django docs)
  • cache set and get methods
like image 189
Reza Torkaman Ahmadi Avatar answered Dec 05 '22 13:12

Reza Torkaman Ahmadi