Django rest框架忽略has_object_permission

时间:2014-03-21 14:35:43

标签: python django django-rest-framework

我正在尝试限制用户对象的访问权限。只有创建者才能修改对象。为了这个目的,就像他们在教程中我所写的那样

class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return False

并将其添加到permission_classes。但仍然任何用户都可以修改任何对象。 如果我添加方法

    def has_permission(self, request, view):
        return False

没有人可以做任何事情。因此,所有行为都由唯一的has_permission方法控制,该方法不提供处理每个对象权限的任何方法。 我做错了什么?这是请求处理程序的代码

class ProblemsHandler(APIView):

    permission_classes = (
        IsOwnerOrReadOnly,
        permissions.IsAuthenticatedOrReadOnly,
    )

    def pre_save(self, request, problem):
        problem.author = request.user

    def get_object(self, request, pk, format):
        try:
            problem = ProblemsModel.objects.get(pk=pk)
            serializer = ProblemsSerializer(problem)
            return Response(serializer.data, status=HTTP_200_OK)
        except ProblemsModel.DoesNotExist:
            raise Http404

    def get_list(self, request, format):
        problems = ProblemsModel.objects.all()
        serializer = ProblemsSerializer(problems, many=True)
        return Response(serializer.data, status=HTTP_200_OK)

    def get(self, request, pk=None, format=None):
        if pk:
            return self.get_object(request, pk, format)
        else:
            return self.get_list(request, format)

    def post(self, request, format=None):
        serializer = ProblemsSerializer(data=request.DATA)
        if serializer.is_valid():
            self.pre_save(request, serializer.object)
            serializer.save()
            return Response(serializer.data, status=HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

    def put(self, request, pk, format=None):
        try:
            problem = ProblemsModel.objects.get(pk=pk)
            serializer = ProblemsSerializer(problem, data=request.DATA)
            if serializer.is_valid():
                self.pre_save(request, serializer.object)
                serializer.save()
                return Response(serializer.data, status=HTTP_200_OK)
            else:
                return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
        except ProblemsModel.DoesNotExist:
            raise Http404

    def delete(self, request, pk, format=None):
        try:
            problem = ProblemsModel.objects.get(pk=pk)
            problem.delete()
            return Response(status=HTTP_204_NO_CONTENT)
        except ProblemsModel.DoesNotExist:
            raise Http404

1 个答案:

答案 0 :(得分:20)

对象的权限检查由DRF在方法APIView.check_object_permissions中完成。

由于您未使用GenericAPIView,因此您需要定义自己的get_object方法,并且必须自己致电check_object_permissions。由于你误用了get_object,你必须检查GET(单个),PUT和DELETE

self.check_object_permissions(self.request, obj)

或许可以更好地了解DRF Generic Views,因为您的用例看起来很像它们。通常get_object应该只返回一个对象并检查权限。