jwt.encode 失败 "Object of type 'bytes' is not JSON serializable"
jwt.encode fails with "Object of type 'bytes' is not JSON serializable"
我正在尝试 return 我的用户在成功登录后向他们发送令牌,但不断收到以下错误:
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'])
尝试导入 json,然后在 return 上使用 json.dumps(response_details):
return Response(json.dumps(response_details), status=response_details['status'])
在 PyJWT 的 旧版本 中,如 1.7 最后需要解码:
jwt.encode(payload, "SECRET_KEY", algorithm='HS256').decode('utf-8')
如果您使用的是 最近的版本,如 2.3.1,则无需转储或解码,一个字符串将已生成为 UTF-8
我正在尝试 return 我的用户在成功登录后向他们发送令牌,但不断收到以下错误:
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'])
尝试导入 json,然后在 return 上使用 json.dumps(response_details):
return Response(json.dumps(response_details), status=response_details['status'])
在 PyJWT 的 旧版本 中,如 1.7 最后需要解码:
jwt.encode(payload, "SECRET_KEY", algorithm='HS256').decode('utf-8')
如果您使用的是 最近的版本,如 2.3.1,则无需转储或解码,一个字符串将已生成为 UTF-8