django GET和POST方法的单独权限类

hfyxw5xn  于 2023-05-30  发布在  Go
关注(0)|答案(1)|浏览(117)

我正在开发一个API,我正在寻找一种方法来选择性地允许访问一个给定的方法,这取决于用户是否经过身份验证。例如:如果用户通过身份验证,则只能访问GET方法,但用户和访客可以访问POST方法。
Django rest框架有一个“permissions.IsAuthenticated”类,但它会影响基于类的视图中的每个方法。下面是我的代码以供参考:

class ServiceSupplierApiView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, *args, **kwargs):
        lista =ServiceSupplier.objects.all()
        serializer = ServiceSupplierSerializer(lista,many = True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        data = {
            'name': request.data.get('name'),
        }
        serializer = ServiceSupplierSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def put(self, request, *args, **kwargs):
        instance = Supplier.objects.get(id = request.data.get('id')) 
        data = {
            'name': request.data.get('name'),
        }

        serializer = ServiceSupplierSerializer(instance = instance,data=data,partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, id, *args, **kwargs):
        instance = self.get_object(id, request.user.id)
        if not instance:
            return Response(
                {"res": "Object with id does not exists"},
                status=status.HTTP_400_BAD_REQUEST
            )
        instance.delete()
        return Response(
            {"res": "Object deleted!"},
            status=status.HTTP_200_OK
        )

我试着查了一下,但没有找到答案。

xzv2uavs

xzv2uavs1#

我想出了这个它有点磨损,但它的工作

def get_permissions(self):
  if self.request.method == 'POST' or self.request.method == 'PUT':
    return [permissions.IsAuthenticated()]
  elif self.request.method == 'DELETE':
    return[permissions.isAdminUser()] # for example
  else:
    return[] # so anyone can view

def get(self, request, *args, **kwargs):
  # logic

.
.
.
.

您不需要声明permission_classes _但是,我认为分离端点会更好,例如将get发送到/suppliers并将post发送到/new-supplier

相关问题