DjandoRestFramework standardize endpoints for methods with different permissions

0

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

views.py

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 I turn it into a single endpoint, for example "/ contact /" for both methods with this variation of permission.

    
asked by anonymous 20.01.2017 / 15:23

1 answer

1

Overwrite 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]
    
23.01.2017 / 04:26