使用“data_key”定义的 Marshmallow 字段与使用“attribute”定义的字段(标识符相反?)之间有什么区别?

Edd*_* E. 7 python schema attributes marshmallow

使用定义marshmallow.Schema名称字段的 (v3.0+)和使用 定义名称字段的另一个(v3.0+)之间有区别吗?fooattribute="bar"bardata_key="foo"

两者似乎都以相同的方式序列化和反序列化字典和其他简单对象:

import marshmallow

class MySchema1(marshmallow.Schema):
    foo = marshmallow.fields.String(attribute="bar")

class MySchema2(marshmallow.Schema):
    bar = marshmallow.fields.String(data_key="foo")

schema1 = MySchema1()
schema2 = MySchema2()

dictionary = {"bar": "hello world"}
assert schema1.dump(dictionary) == schema2.dump(dictionary)
assert schema1.load(schema1.dump(dictionary)) == schema2.load(schema2.dump(dictionary))

class Thingy:
    def __init__(self):
        self.bar = "hello world"

instance = Thingy()
assert schema1.dump(instance) == schema2.dump(instance)
assert schema1.load(schema1.dump(instance)) == schema2.load(schema2.dump(instance))
Run Code Online (Sandbox Code Playgroud)

以上通过。目前这不会在我的项目中造成任何错误,但我很好奇有什么区别!提前致谢。

Jér*_*ôme 8

你是对的。两种模式的行为相同。

这可以被视为冗余 API:从您的示例中,您可能想知道为什么要attribute提供data_key相同的功能。

实际上,同时拥有两者很有用,因为它允许为加载键和转储键指定无效的 python 变量名称。

class MySchema(marshmallow.Schema):
    foo = marshmallow.fields.String(attribute="bar-load", data_key="bar-dump")
Run Code Online (Sandbox Code Playgroud)

AFAIK,这就是我们没有加入attribute棉花糖的原因。可能还有其他原因,但这一个似乎已经是一个很好的原因了。