Python:jsonify中的str(bytes object)导致TypeError:“ bytes”类型的对象不可JSON序列化

时间:2018-07-23 14:53:52

标签: python json flask request backend

我向我的API发送了一个请求,但它引发TypeError:“字节”类型的对象不可JSON序列化。它还会返回500 INTERNAL SERVER ERROR。

代码:

def login():
    data = request.json
    if(data['token'] != 'xxxxxxxxxxx'):
        return jsonify(), 401
    user = User.objects(npm=data['npm']).first()
    if(user == None):
        del data['token']
        user = User(**data)
        user.major = Major.objects(name=data['major']).first()
        user.role = 'user'
        user.save()
    token = jwt.encode({
        'user_id': str(user.id)
    }, secret_key, algorithm='HS256')
    return jsonify({
        'user_id': str(user.id),
        'token': token,
        'major_id': str(user.major.id)
    }), 200

跟踪:

Traceback (most recent call last):
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\users\anisha\env\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\users\anisha\env\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "c:\users\anisha\env\lib\site-packages\flask_cors\decorator.py", line 128, in wrapped_function
resp = make_response(f(*args, **kwargs))
File "C:\Users\Anisha\sunjadv2-server\app.py", line 69, in login
'major_id': str(user.major.id)
File "c:\users\anisha\env\lib\site-packages\flask\json\__init__.py", line 321, in jsonify
dumps(data, indent=indent, separators=separators) + '\n',
File "c:\users\anisha\env\lib\site-packages\flask\json\__init__.py", line 179, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "c:\users\anisha\env\lib\site-packages\flask\json\__init__.py", line 81, in default
return _json.JSONEncoder.default(self, o)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'bytes' is not JSON serializable

当我执行print("major_id: " + str(user.major.id))时,它将打印 major_id:5b55e986f15bf336e0b820fe 进行管理。为什么将str(user.major.id)视为jsonify中的字节类型?我试图删除'major_id': str(user.major.id),但随后的行'token': token将导致相同的错误。

谢谢。

1 个答案:

答案 0 :(得分:4)

似乎您的数据可能未正确解码。您可以在对数据进行json解码之前尝试对其进行解码。

例如,与其直接使用令牌,不如尝试使用:token.decode('utf-8')