【问题标题】:getting AttributeError: 'str' object has no attribute 'decode' in rest_framework_simplejwt.serializers.TokenObtainPairSerializer.get_token()获取AttributeError:'str'对象在rest_framework_simplejwt.serializers.TokenObtainPairSerializer.get_token()中没有属性'decode'
【发布时间】:2021-07-06 15:21:00
【问题描述】:

我正在开发与选举相关的网络应用程序并尝试使用rest_framework_simplejwt.serializers 实现授权令牌概念,并且在运行此代码时遇到与str 类相关的错误,如下所示: AttributeError: 'str' object has no attribute 'decode' 从这部分代码: data['refresh'] = str(refresh)

class AuthTokenObtainSerializer(TokenObtainPairSerializer):
    """
    Seializer for th user authentication object.

    Returns
    -------
        json: 'access' and 'token'
    """
    default_error_messages = {
        'no_active_account': _('No active account found with the given credentials')  # noqa: E501
    }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['password'] = serializers.CharField(
            style={'input_type': 'password'},
            trim_whitespace=False
        )
        self.fields['face_image'] = serializers.ImageField()

    def validate(self, attrs):
        """
        Validates and authenticate the user.
        """
        citizenship_number = attrs.get('citizenship_number')
        password = attrs.get('password')
        face_image = attrs.get('face_image')

        face_id = FaceIdAuthBackend()
        user = face_id.authenticate(
            citizenship_number=citizenship_number,
            password=password,
            face_id=face_image
        )

        if user is None or not user.is_active:
            raise exceptions.AuthenticationFailed(
                self.error_messages['no_active_account'],
                'no_active_account',
            )

        update_last_login(None, user)

        data = {}
        refresh = self.get_token(user)

        data['refresh'] = str(refresh)

        data['access'] = str(refresh.access_token)

        return data

请帮我解决这个问题......

【问题讨论】:

  • 为什么要同时转换 refresh 和 refresh.access_token?
  • 以包含访问数据和令牌数据的json返回

标签: python django-rest-framework auth-token


【解决方案1】:

虽然我在不同来源寻找解决方案,但我知道这个特定问题来自 PyJWT 包的最新版本,所以我必须将其降级到 v1.7.1,现在我不再遇到这个问题了。

来源:https://github.com/jazzband/django-rest-framework-simplejwt/issues/346

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-01
    • 2014-05-26
    • 2021-07-05
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    • 2015-02-17
    相关资源
    最近更新 更多