I use some permission checks inside overridden check_permissions. I get the instance I will work with using get_object. I know that after this the get_object method will be called again - during retrieve or destroy methods. So I use caching (@lru_cache). See full example below.
from functools import lru_cache
from rest_framework.exceptions import PermissionDenied
from rest_framework.generics import RetrieveDestroyAPIView
class UserView(RetrieveDestroyAPIView):
permission_classes = [ProjectAdminOnly]
serializer_class = UserSerializer
@lru_cache
def get_object(self, *args, **kwargs):
return UserService.get(self.kwargs['user_id'])
def check_permissions(self, request):
super().check_permissions(request)
user = self.get_object()
# Only within the same project
if self.request.user.project != user.project:
raise PermissionDenied()
This code passes my tests successfully, but I wonder is there any unsafe situation in which the caching will do the bad service for me?