sqlachemy 和 marshmallow 的序列化程序错误

Serializer error with sqlachemy and marshmallow

根据官方documentation我尝试以json格式

获取Vehicle class的所有实例
Session = sessionmaker(bind=engine)
session = Session()
from models import Vehicle
from marshmallow_sqlalchemy import ModelSchema


class VehicleShema(ModelSchema):
    class Meta:
        model = Vehicle

vehicles = session.query(Vehicle).all()

vehicle_schema = VehicleShema()

session.add(vehicles)
session.commit()

dump_data = vehicle_schema.dump(vehicles)

print(dump_data)

但是报错

    raise exc.UnmappedInstanceError(instance)
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped

我认为问题可能出在 queriset 的定义上 vehicles = session.query(Vehicle).all() 但我没有找到其他方法。

然后我只调用一个实例vehicles = session.query(Vehicle).first()一切正常。

错误回溯

Traceback (most recent call last):
  File "/home/y700/projects/viastart/sqlalchemy/orm/session.py", line 1955, in add
    state = attributes.instance_state(instance)
AttributeError: 'list' object has no attribute '_sa_instance_state'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "get_vehisle_by_id.py", line 11, in <module>
    session.add(vehicles)
  File "/home/y700/projects/viastart/sqlalchemy/orm/session.py", line 1957, in add
    raise exc.UnmappedInstanceError(instance)
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped

您没有指定是否要将 vechiles 序列化为集合,即列表。

vehicle_schema = VehicleShema(many=True)

这应该可以解决问题。请参考 marshmallow docs.

上发布的示例

根据我的评论使用 schema.dump(vehicles, many=True):

要进行扩展,您最终可能会想要使用如下实用程序:

def dumpData(load_object, schema, many=False):
    try:
        answer = schema.dump(load_object, many=many)
    except ValidationError as errors:
        raise InvalidDump(errors, status_code=400)
    return answer
class InvalidDump(Exception):
    """error for dumping data"""
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        """include marshmallow validation errors in response"""
        rv = dict(self.payload or ())
        rv['message'] = self.message.messages
        return rv

然后为每个数据转储创建一个具有该棉花糖模式的版本。

def dumpVehicle(load_object, many=False):
    return dumpData(load_object, schema=vehicle_schema_full, many=many)