Djandorestframework standardize endpoints for methods with different permissions

Asked

Viewed 94 times

0

I am using Django 1.10 with DRF lib. I created an Endpoint /api/contact/ and in this endpoint I apply 2 methods (GET and POST), and GET can only be viewed with permission, and POST can be requested without permission. The problem is in the standard creation of endpoints. See below the creation of viewsets and urls:

py views.

class ContactList(APIView):
    serializer_class = serializers.ContactSerializer

    def get(self, request, format=None):
       model = models.Contact.objects.all()
       serializer = serializers.ContactSerializer(model, many=True)
       return Response(serializer.data)

class ContactSend(APIView):
    permission_classes = (AllowAny,)
    serializer_class = serializers.ContactSerializer

    def post(self, request, format=None):
       serializer = self.serializer_class(data=request.data)
       if serializer.is_valid():
          serializer.save()
          return Response(serializer.data, status=status.HTTP_201_CREATED)
       else:
          return Response({"message":"403 Forbiden"},  status=status.HTTP_409_CONFLICT)

Sac/urls.py

urlpatterns = [
   url(r'^contact/$', views.ContactSend.as_view(), name="contact_send"),
   url(r'^contact/send/$', views.ContactList.as_view(), name="contact_list"),
]

How could you turn it into a single endpoint, for example "/contact/" for both methods with this permission variation.

1 answer

1

Overwrite the method .get_permissions is a solution:

class ContactView(ListCreateAPIView):

      ...

    def get_permissions(self):
        if self.request.method == 'POST':
            self.permission_classes = (AllowAny,)
        return [permission() for permission in self.permission_classes]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.