我试图限制用户对对象的访问。只有创建者才可以修改对象。为此,就像他们在我写的教程中所说的那样

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

最佳答案

对象的权限检查由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应该只返回一个对象并检查权限。

关于python - Django rest框架忽略has_object_permission,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22561698/

10-10 21:27