升级到3.5.0 marshmallow后出现了“未知字段”问题。

7

我项目中的依赖项已更新

更新前

marshmallow-sqlalchemy==0.17.0
marshmallow==3.0.0b6

之后

marshmallow-sqlalchemy==0.21.0
marshmallow==3.5.0

我有这样一个模型(简化版):

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class MyModel(Base):
    __tablename__ = 'my_model'

    id = Column(BigInteger, primary_key=True)
    field_name = Column(String)
    password = Column(String)

以及架构

from marshmallow import fields
from marshmallow_sqlalchemy import (
    ModelSchema,
    field_for,
)
class RegistrarSchema(ModelSchema):
    class Meta:
        model = MyModel

    other_field_name = fields.Function(lambda obj: obj.field_name)
    field_name = field_for(MyModel, 'field_name', load_from='other_field_name')

    password = fields.Method("get_password")

    def get_password(self, obj):
        return decrypt_password(obj)

    def load(self, data, session=None, instance=None, transient=False, *args, **kwargs):
        if 'password' in data:
            password = data['password']
            instance = encrypt_password(password, instance)
        return super(ModelSchema, self).load(
            data, *args, session=session, instance=instance,
            transient=transient, **kwargs
        )

使用这段代码,我可以调用

RegistrarSchema.load(data={'other_field_name': 'my_value'}, instance=instance, session=session)

这个值将会保存到我的数据库中的 field_name 字段。

更新以后我失去了这个功能 - 现在我得到了

File "myfile.py", line 116, in load
    transient=transient, **kwargs
  File "/usr/local/lib/python3.7/dist-packages/marshmallow_sqlalchemy/schema.py", line 214, in load
    return super().load(data, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/marshmallow/schema.py", line 723, in load
    data, many=many, partial=partial, unknown=unknown, postprocess=True
  File "/usr/local/lib/python3.7/dist-packages/marshmallow/schema.py", line 904, in _do_load
    raise exc
marshmallow.exceptions.ValidationError: {'other_field_name': ['Unknown field.']}

当更新密码时,出现完全相同的错误 -

RegistrarSchema.load(data={'password': 'my_value'}, instance=instance, session=session)

我没有亲自编写这段代码,也无法联系开发者。

根据我的理解,第一种情况的目标是让用户能够以两种方式进行编写 - data={'my_field': 'value'}data={'other_field_name': 'value'}。第一种情况在新版本中仍然有效,但第二种情况无效。

在密码方面的目标是通过加密/解密数据来使序列化/反序列化更加复杂。

我阅读了更新说明,但未能找到与此问题有关的任何具体信息,有人能帮忙吗?


https://marshmallow.readthedocs.io/en/stable/upgrading.html#schemas-raise-validationerror-when-deserializing-data-with-unknown-keys - Jérôme
1个回答

13

在 v3. 中,marshmallow 将默认行为从 EXCLUDE 更改为 RAISE https://marshmallow.readthedocs.io/en/stable/quickstart.html#handling-unknown-fields

您可以通过在模式的 class Meta 中指定 unknown 来恢复旧行为:

from marshmallow import EXCLUDE
class UserSchema(Schema):
    class Meta:
        unknown = EXCLUDE

在实例化时,

schema = UserSchema(unknown=EXCLUDE)

或在调用load时。

UserSchema().load(data, unknown=EXCLUDE)

在加载时设置的未知选项值将会覆盖实例化时应用的值,而后者将会覆盖在类元数据中定义的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接