Django REST Framework - Separate permissions per methods

后端 未结 7 1979
栀梦
栀梦 2020-12-23 13:19

I am writing an API using Django REST Framework and I am wondering if can specify permissions per method when using class based views.

Reading the documentation I se

7条回答
  •  误落风尘
    2020-12-23 13:56

    I ran into this problem and really wanted to use the @permission_classes decorator to mark some custom view methods with specific permissions. I ended up coming up with a mixin:

    class PermissionsPerMethodMixin(object):
        def get_permissions(self):
            """
            Allows overriding default permissions with @permission_classes
            """
            view = getattr(self, self.action)
            if hasattr(view, 'permission_classes'):
                return [permission_class() for permission_class in view.permission_classes]
            return super().get_permissions()
    

    An example use case:

    from rest_framework.decorators import action, permission_classes  # other imports elided
    
    class MyViewset(PermissionsPerMethodMixin, viewsets.ModelViewSet):
        permission_classes = (IsAuthenticatedOrReadOnly,)  # used for default ViewSet endpoints
        queryset = MyModel.objects.all()
        serializer_class = MySerializer
    
        @action(detail=False, methods=['get'])
        @permission_classes((IsAuthenticated,))  # overrides IsAuthenticatedOrReadOnly
        def search(self, request):
            return do_search(request)  # ...
    

提交回复
热议问题