'User' 类型的对象不可 JSON 序列化(父 class)
Object of type 'User' is not JSON serializable (Parent class)
我正在尝试通过我的 Flask API 在我的数据库中插入一条记录。 User 和 Project classes 之间的关系是一对多的(一个 User 可以有多个项目)。我在插入新用户时没有问题,但是当我尝试在数据库中插入新项目时,它确实有效,但无法将项目中的用户属性转换为 JSON。这是我的代码:
用户模型文件:
class Usuario(db.Model):
id = db.Column(db.BigInteger, primary_key=True)
login = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
nome = db.Column(db.String(80), nullable=False)
senha = db.Column(db.String(80), nullable=False)
telefone = db.Column(db.String(80))
receivedNotification = db.Column(
db.Boolean, default=False, nullable=False)
receivedEmail = db.Column(db.Boolean, default=False, nullable=False)
emailVerificated = db.Column(db.Boolean, default=False, nullable=False)
imagem = db.Column(db.LargeBinary(length=(2 ** 32) - 1))
def __init__(self, login='', email='', nome='', senha='',
telefone='', received_notification=False,
received_email=False, email_verificated=False, imagem=None, init_dict=None):
if init_dict is None:
self.login = login
self.email = email
self.nome = nome
self.senha = senha
self.telefone = telefone
self.receivedNotification = received_notification
self.receivedEmail = received_email
self.emailVerificated = email_verificated
self.imagem = imagem
else:
for key in init_dict:
setattr(self, key, init_dict[key])
class UsuarioSchema(ma.Schema):
class Meta:
fields = ('id', 'login', 'email', 'nome', 'telefone',
'receivedNotification', 'receivedEmail', 'emailVerificated', 'imagem')
user_schema = UsuarioSchema()
users_schema = UsuarioSchema(many=True)
项目模型文件:
class Projeto(db.Model):
codigo = db.Column(db.BigInteger, primary_key=True)
nome = db.Column(db.String(100))
descricao = db.Column(db.String(200))
dataCriacao = db.Column(db.Date)
dataPrevFinalizacao = db.Column(db.Date)
dataFinalizacao = db.Column(db.Date)
usuarioAdmId = db.Column(db.BigInteger,
db.ForeignKey('usuario.id'), nullable=False)
usuarioAdm = db.relationship('Usuario',
backref=db.backref('projetos', lazy=True))
def __init__(self, nome, descricao, data_criacao,
data_prev_finalizacao, usuario_adm_id, data_finalizacao=None):
self.nome = nome
self.descricao = descricao
self.dataCriacao = data_criacao
self.dataPrevFinalizacao = data_prev_finalizacao
self.dataFinalizacao = data_finalizacao
self.usuarioAdmId = usuario_adm_id
class ProjetoSchema(ma.Schema):
class Meta:
fields = ('nome', 'descricao', 'dataCriacao',
'dataPrevFinalizacao', 'dataFinalizacao', 'usuarioAdm')
projeto_schema = ProjetoSchema()
projetos_schema = ProjetoSchema(many=True)
我添加项目的路由代码:
@projeto_controller.route(mapping, methods=['POST'])
def add_projeto():
nome = request.json['nome']
descricao = request.json['descricao']
data_criacao = request.json['dataCriacao']
data_criacao = datetime.strptime(
data_criacao, '%b %d, %Y %I:%M:%S %p').date()
data_prev_finalizacao = request.json['dataPrevFinalizacao']
data_prev_finalizacao = datetime.strptime(
data_prev_finalizacao, '%b %d, %Y %I:%M:%S %p').date()
usuario_adm_id = request.json['usuarioAdm']['id']
usuario_adm = request.json['usuarioAdm']
usuario = mUsuario.Usuario.query.get(usuario_adm_id)
usuarioAdm = usuario
new_projeto = mProjeto.Projeto(nome=nome, descricao=descricao,
data_criacao=data_criacao,
data_prev_finalizacao=data_prev_finalizacao,
usuario_adm_id=usuario_adm_id)
new_projeto.usuarioAdm = usuarioAdm
usuarioAdm.projetos.append(new_projeto)
db.session.commit()
return mProjeto.projeto_schema.jsonify(new_projeto)
错误信息:
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/user/Python/KeepSoftPythonAPI/controller/ProjetoController.py", line 93, in add_projeto
return mProjeto.projeto_schema.jsonify(new_projeto)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask_marshmallow/schema.py", line 42, in jsonify
return flask.jsonify(data, *args, **kwargs)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/json/__init__.py", line 321, in jsonify
dumps(data, indent=indent, separators=separators) + '\n',
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/json/__init__.py", line 179, in dumps
rv = _json.dumps(obj, **kwargs)
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 405, in _iterencode_dict
yield from chunks
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 438, in _iterencode
o = _default(o)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/json/__init__.py", line 81, in default
return _json.JSONEncoder.default(self, o)
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Usuario is not JSON serializable
我预计会返回一个项目 JSON,因此我可以转换为存在于我的移动应用程序中的项目 class。
你应该有一个功能,就是returns把Projeto
的对象变成class的字典格式,然后把它转换成jsonify
就可以了。像
def get_objects(self):
"""
This function creates a dictionary and assigns
the keys of the dictionary with the objects of
the class and returns it in a json format.
"""
data = {
'nome': self.nome,
'descricao': self.descricao,
'data_criacao': self.dataCriacao,
'data_prev_finalizacao': self.dataPrevFinalizacao,
'data_finalizacao': self.dataFinalizacao,
'usuario_adm_id': self.usuarioAdmId
}
return jsonify(data)
如果您需要以 JSON 格式为模型返回数据,则需要以 JSON 格式返回数据。目前使用这行代码,
return mProjeto.projeto_schema.jsonify(new_projeto)
您正在尝试将 Usuario 和 Projeto 对象转换为 JSON 对象,这不是 jsonify
函数支持的有效数据类型。这就是消息所指示的
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Usuario is not JSON serializable
也可以对 Usuario class 执行相同的操作。
经过大量搜索,终于解决了我的问题。我必须明确定义 ProjetoSchema
class 中定义的 object usuario
是嵌套的 object,因此只有在检索 Projeto
时才使用它们,此 object 将作为 JSON.
正确加载
所以,现在这是修改后的架构:
class ProjetoSchema(ma.Schema):
class Meta:
fields = ('codigo', 'nome', 'descricao', 'dataCriacao',
'dataPrevFinalizacao', 'dataFinalizacao', 'usuarioAdm')
model = Projeto
usuarioAdm = ma.Nested('UsuarioSchema', exclude=('projetos',))
perfis = ma.Nested('PerfilSchema', many=True, exclude=('projeto',))
projeto_schema = ProjetoSchema()
projetos_schema = ProjetoSchema(many=True)
这是修改后的 UsuarioSchema:
class UsuarioSchema(ma.Schema):
class Meta:
fields = ('id', 'login', 'email', 'nome', 'telefone', 'receivedNotification',
'receivedEmail', 'emailVerificated', 'imagem')
model = Usuario
projetos = ma.Nested('ProjetoSchema', many=True, exclude=('usuarioAdm',))
perfis = ma.Nested('PerfilSchema', many=True, exclude=('usuario',))
user_schema = UsuarioSchema()
users_schema = UsuarioSchema(many=True)
这样,我就不需要像在获得最终代码之前那样处理无限嵌套的 object。其中一些行毕竟不是必需的,因为当我检索 Usuario
时,我省略了包含它的字段 Projeto
children 并且当检索 Projeto
时,它正确显示现在是 parent。
请原谅我的英语,我是巴西人。
感谢所有提示和解决方案。
我正在尝试通过我的 Flask API 在我的数据库中插入一条记录。 User 和 Project classes 之间的关系是一对多的(一个 User 可以有多个项目)。我在插入新用户时没有问题,但是当我尝试在数据库中插入新项目时,它确实有效,但无法将项目中的用户属性转换为 JSON。这是我的代码:
用户模型文件:
class Usuario(db.Model):
id = db.Column(db.BigInteger, primary_key=True)
login = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
nome = db.Column(db.String(80), nullable=False)
senha = db.Column(db.String(80), nullable=False)
telefone = db.Column(db.String(80))
receivedNotification = db.Column(
db.Boolean, default=False, nullable=False)
receivedEmail = db.Column(db.Boolean, default=False, nullable=False)
emailVerificated = db.Column(db.Boolean, default=False, nullable=False)
imagem = db.Column(db.LargeBinary(length=(2 ** 32) - 1))
def __init__(self, login='', email='', nome='', senha='',
telefone='', received_notification=False,
received_email=False, email_verificated=False, imagem=None, init_dict=None):
if init_dict is None:
self.login = login
self.email = email
self.nome = nome
self.senha = senha
self.telefone = telefone
self.receivedNotification = received_notification
self.receivedEmail = received_email
self.emailVerificated = email_verificated
self.imagem = imagem
else:
for key in init_dict:
setattr(self, key, init_dict[key])
class UsuarioSchema(ma.Schema):
class Meta:
fields = ('id', 'login', 'email', 'nome', 'telefone',
'receivedNotification', 'receivedEmail', 'emailVerificated', 'imagem')
user_schema = UsuarioSchema()
users_schema = UsuarioSchema(many=True)
项目模型文件:
class Projeto(db.Model):
codigo = db.Column(db.BigInteger, primary_key=True)
nome = db.Column(db.String(100))
descricao = db.Column(db.String(200))
dataCriacao = db.Column(db.Date)
dataPrevFinalizacao = db.Column(db.Date)
dataFinalizacao = db.Column(db.Date)
usuarioAdmId = db.Column(db.BigInteger,
db.ForeignKey('usuario.id'), nullable=False)
usuarioAdm = db.relationship('Usuario',
backref=db.backref('projetos', lazy=True))
def __init__(self, nome, descricao, data_criacao,
data_prev_finalizacao, usuario_adm_id, data_finalizacao=None):
self.nome = nome
self.descricao = descricao
self.dataCriacao = data_criacao
self.dataPrevFinalizacao = data_prev_finalizacao
self.dataFinalizacao = data_finalizacao
self.usuarioAdmId = usuario_adm_id
class ProjetoSchema(ma.Schema):
class Meta:
fields = ('nome', 'descricao', 'dataCriacao',
'dataPrevFinalizacao', 'dataFinalizacao', 'usuarioAdm')
projeto_schema = ProjetoSchema()
projetos_schema = ProjetoSchema(many=True)
我添加项目的路由代码:
@projeto_controller.route(mapping, methods=['POST'])
def add_projeto():
nome = request.json['nome']
descricao = request.json['descricao']
data_criacao = request.json['dataCriacao']
data_criacao = datetime.strptime(
data_criacao, '%b %d, %Y %I:%M:%S %p').date()
data_prev_finalizacao = request.json['dataPrevFinalizacao']
data_prev_finalizacao = datetime.strptime(
data_prev_finalizacao, '%b %d, %Y %I:%M:%S %p').date()
usuario_adm_id = request.json['usuarioAdm']['id']
usuario_adm = request.json['usuarioAdm']
usuario = mUsuario.Usuario.query.get(usuario_adm_id)
usuarioAdm = usuario
new_projeto = mProjeto.Projeto(nome=nome, descricao=descricao,
data_criacao=data_criacao,
data_prev_finalizacao=data_prev_finalizacao,
usuario_adm_id=usuario_adm_id)
new_projeto.usuarioAdm = usuarioAdm
usuarioAdm.projetos.append(new_projeto)
db.session.commit()
return mProjeto.projeto_schema.jsonify(new_projeto)
错误信息:
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/user/Python/KeepSoftPythonAPI/controller/ProjetoController.py", line 93, in add_projeto
return mProjeto.projeto_schema.jsonify(new_projeto)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask_marshmallow/schema.py", line 42, in jsonify
return flask.jsonify(data, *args, **kwargs)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/json/__init__.py", line 321, in jsonify
dumps(data, indent=indent, separators=separators) + '\n',
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/json/__init__.py", line 179, in dumps
rv = _json.dumps(obj, **kwargs)
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 405, in _iterencode_dict
yield from chunks
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 438, in _iterencode
o = _default(o)
File "/anaconda3/envs/KeepSoft/lib/python3.7/site-packages/flask/json/__init__.py", line 81, in default
return _json.JSONEncoder.default(self, o)
File "/anaconda3/envs/KeepSoft/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Usuario is not JSON serializable
我预计会返回一个项目 JSON,因此我可以转换为存在于我的移动应用程序中的项目 class。
你应该有一个功能,就是returns把Projeto
的对象变成class的字典格式,然后把它转换成jsonify
就可以了。像
def get_objects(self):
"""
This function creates a dictionary and assigns
the keys of the dictionary with the objects of
the class and returns it in a json format.
"""
data = {
'nome': self.nome,
'descricao': self.descricao,
'data_criacao': self.dataCriacao,
'data_prev_finalizacao': self.dataPrevFinalizacao,
'data_finalizacao': self.dataFinalizacao,
'usuario_adm_id': self.usuarioAdmId
}
return jsonify(data)
如果您需要以 JSON 格式为模型返回数据,则需要以 JSON 格式返回数据。目前使用这行代码,
return mProjeto.projeto_schema.jsonify(new_projeto)
您正在尝试将 Usuario 和 Projeto 对象转换为 JSON 对象,这不是 jsonify
函数支持的有效数据类型。这就是消息所指示的
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Usuario is not JSON serializable
也可以对 Usuario class 执行相同的操作。
经过大量搜索,终于解决了我的问题。我必须明确定义 ProjetoSchema
class 中定义的 object usuario
是嵌套的 object,因此只有在检索 Projeto
时才使用它们,此 object 将作为 JSON.
所以,现在这是修改后的架构:
class ProjetoSchema(ma.Schema):
class Meta:
fields = ('codigo', 'nome', 'descricao', 'dataCriacao',
'dataPrevFinalizacao', 'dataFinalizacao', 'usuarioAdm')
model = Projeto
usuarioAdm = ma.Nested('UsuarioSchema', exclude=('projetos',))
perfis = ma.Nested('PerfilSchema', many=True, exclude=('projeto',))
projeto_schema = ProjetoSchema()
projetos_schema = ProjetoSchema(many=True)
这是修改后的 UsuarioSchema:
class UsuarioSchema(ma.Schema):
class Meta:
fields = ('id', 'login', 'email', 'nome', 'telefone', 'receivedNotification',
'receivedEmail', 'emailVerificated', 'imagem')
model = Usuario
projetos = ma.Nested('ProjetoSchema', many=True, exclude=('usuarioAdm',))
perfis = ma.Nested('PerfilSchema', many=True, exclude=('usuario',))
user_schema = UsuarioSchema()
users_schema = UsuarioSchema(many=True)
这样,我就不需要像在获得最终代码之前那样处理无限嵌套的 object。其中一些行毕竟不是必需的,因为当我检索 Usuario
时,我省略了包含它的字段 Projeto
children 并且当检索 Projeto
时,它正确显示现在是 parent。
请原谅我的英语,我是巴西人。
感谢所有提示和解决方案。