我正在开发一个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
)
我试着查了一下,但没有找到答案。
1条答案
按热度按时间xzv2uavs1#
我想出了这个它有点磨损,但它的工作
您不需要声明
permission_classes
_但是,我认为分离端点会更好,例如将get发送到/suppliers
并将post发送到/new-supplier