3 ms·
I had this problem a couple of days ago. I wanted to use Django' last_modified decorator like this: from django.utils.decorators import method_decorator
by Walkman 10y ago
I had this problem a couple of days ago. I wanted to use Django' last_modified decorator like this:
from django.utils.decorators import method_decorator
from django.views.decorators.http import last_modified
from rest_framework import viewsets
class SomeClassBasedView(viewsets.ViewSet):
def last_modified_time(self, request):
return cache.get_or_set('key', some_date)
@method_decorator(last_modified(last_modified_time))
def get_some_object(self):
# expensive DB operation
Of course it blew up, even when I decorated the last_modified_time with @staticmethod or @classmethod so I had two choices
1. The misleading simple function definition inside the class body, like:
class SomeClassBasedView(viewsets.ViewSet):
def last_modified_time(request):
return cache.get_or_set('key', some_date)
@method_decorator(last_modified(last_modified_time))
def get_some_object(self):
# expensive DB operation
The biggest problem with this that it can be confusing for our junior developers (might be even strange for seasoned Pythonistas).
Also an IDE (e.g. PyCharm) marks the request argument with a different color making it even more confusing.
2. Define the function outside of the class body (where it doesn't belong...):
def last_modified_time(request):
return cache.get_or_set('key', some_date)
class SomeClassBasedView(viewsets.ViewSet):
@method_decorator(last_modified(last_modified_time))
def get_some_object(self):
# expensive DB operation