【问题标题】:jwt.encode fails with "Object of type 'bytes' is not JSON serializable"jwt.encode 失败并显示“'bytes' 类型的对象不是 JSON 可序列化的”
【发布时间】:2018-10-10 19:13:16
【问题描述】:

我试图在我的用户成功登录后向他们返回一个令牌,但不断收到以下错误:

TypeError: Object of type 'bytes' is not JSON serializable

我该如何解决?到目前为止,这是我的代码:

   if user:
        selected_user = {
            'email': user.__dict__['email'],
            'password': user.__dict__['password'],
            'account_type': user.__dict__['account_type'],
            'token': ''
        }

        if bcrypt.checkpw(request.data['password'].encode('utf8'), selected_user['password'].encode('utf8')):
            payload = {
                'email': selected_user.email,
                'account_type': selected_user.account_type
            }
            selected_user['token'] = jwt.encode(payload, "SECRET_KEY")
            response_details = {
                'data': selected_user,
                'message': 'Login successful.',
                'code': '200',
                'status': HTTP_200_OK
            }
            return Response(response_details, status=response_details['status'])
        else:
            response_details = {
                'message': "Invalid password.",
                'code': "400",
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response_details, status=response_details['status'])
    else:
        response_details = {
            'message': "Invalid email and password combination.",
            'code': "400",
            'status': HTTP_400_BAD_REQUEST
        }
        return Response(response_details, status=response_details['status'])

【问题讨论】:

标签: python django jwt token access-token


【解决方案1】:

旧版本的 PyJWT 中,例如 1.7 decode 是最后需要的:

jwt.encode(payload, "SECRET_KEY", algorithm='HS256').decode('utf-8')

如果您使用的是最近的版本,如 2.3.1,则无需转储或解码,将生成一个已在 UTF-8 中的字符串

【讨论】:

    【解决方案2】:

    尝试导入 json,然后在返回时使用 json.dumps(response_details):

     return Response(json.dumps(response_details), status=response_details['status'])
    

    【讨论】:

    • 在代码中没有达到这一点,在客户端我得到500 (Internal Server Error)
    • 这个错误确实会抛出一个内部服务器错误,即使它发生在返回方法上
    猜你喜欢
    • 2022-12-12
    • 2018-12-31
    • 2021-01-31
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    相关资源
    最近更新 更多