Home > Back-end >  Return response statement is not returning any response
Return response statement is not returning any response

Time:09-16

I am creating a logout view to logout from my django restframework using simplejwt. There is no direct way to logout so only blacklisting the refresh token is the workarround.

Those print statements works expectedly so it does blacklist the tokens but the return statement doesn't return anything, why is that and how may I return a Response?I am guessing the save function doesnt return anything, is it ture?

class LogoutSerializer(serializers.Serializer):
    refresh = serializers.CharField()

    def validate(self, attrs):
        self.token = attrs['refresh']
        return attrs

    def save(self, **kwargs):
        try:
            RefreshToken(self.token).blacklist()
            print('done')
            return Response({'msg':'token has been blacklisted'})
       

        except TokenError:
            print('not done')
            return Response({'msg':'token is expired or blacklisted'})

views.py

class LogoutAPIView(APIView):
    serializer_class = LogoutSerializer
    permission_classes = [IsAuthenticated]

    def post(self, request):
        serializer = self.serializer_class(data = request.data)
        serializer.is_valid(raise_exception = True)
        serializer.save()

        return Response(status = status.HTTP_204_NO_CONTENT)

CodePudding user response:

def post(self, request):
    serializer = self.serializer_class(data = request.data)
    serializer.is_valid(raise_exception = True)
    serializer.save()

    return Response(status = status.HTTP_204_NO_CONTENT) # this is the response that you're actually returning to the client.

If you want to return the responses in the serializer you can do:

class LogoutSerializer(serializers.Serializer):
    refresh = serializers.CharField()

    def validate(self, attrs):
        self.token = attrs['refresh']
        return attrs

    def save(self, **kwargs):
        RefreshToken(self.token).blacklist()

then:

def post(self, request):
    serializer = self.serializer_class(data = request.data)
    serializer.is_valid(raise_exception = True)
    try:
        serializer.save()
        return Response({'msg':'token has been blacklisted'})
    except TokenError:
        return Response({'msg':'token is expired or blacklisted'})
  • Related