How to use Last-Modified header with Django Rest Framework ViewSet?

Solution 1:

I checked package mentioned by @Makarand Bauskar. However I wasn't satisfied. It's not active and it uses custom way how to work/deal with Last-Modified header. So I decided to create new package django-rest-framework-condition that does:

  1. Re-uses implementation from Django
    • it will get fixes from Django
    • you can use it same way as described in Django's docs
  2. Provides both @last_modified and @etag decorator

To install it:

pip install django-rest-framework-condition

Usage:

from django.contrib.auth import get_user_model
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework_condition import last_modified


def my_last_modified(request, *args, **kwargs):
    return datetime(2019, 1, 1)


class SubscriptionViewSet(ViewSet):
    @last_modified(my_last_modified)
    def list(self, request):
        data = {'user_count': get_user_model().objects.count()}
        return Response(data)