jwt.encode失败,“对象类型'字节'不是JSON可序列化的”

时间:2018-04-30 16:43:47

标签: python django jwt token access-token

我尝试在成功登录后向用户返回令牌,但不断收到以下错误:

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'])

1 个答案:

答案 0 :(得分:1)

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

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