使用 django-rest-framework-simplejwt 注册后返回令牌

2024-04-09

我正在使用 django-rest-framework-simplejwt,想知道注册用户后是否可以返回令牌?

This https://stackoverflow.com/questions/37622616/django-rest-framework-return-auth-token-after-registration帖子有另一个 jwt 包的解决方案,我想知道如何为 simplejwt 做类似的事情?

thanks


我刚刚解决了我自己的问题。如果您有任何意见,请告诉我。谢谢!

序列化器.py

class RegisterUserSerializer(serializers.ModelSerializer):
    """Serializer for creating user objects."""

    tokens = serializers.SerializerMethodField()

    class Meta:
        model = models.User
        fields = ('id', 'password', 'email', 'tokens')
        extra_kwargs = {'password': {'write_only': True}}

    def get_tokens(self, user):
        tokens = RefreshToken.for_user(user)
        refresh = text_type(tokens)
        access = text_type(tokens.access_token)
        data = {
            "refresh": refresh,
            "access": access
        }
        return data

    def create(self, validated_data):
        user = models.User(
            email=validated_data['email']
        )
        user.set_password(validated_data['password'])
        user.save()    
        return user

views.py

class UserListView(generics.ListCreateAPIView):
    """Handles creating and listing Users."""
    queryset = User.objects.all()

def create(self, request, *args, **kwargs):
        serializer = RegisterUserSerializer(data=request.data)
        if serializer.is_valid():
            self.perform_create(serializer)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 django-rest-framework-simplejwt 注册后返回令牌 的相关文章

随机推荐