我尝试使用 棉花糖 2.18.0 在 python 3.7 用于验证数据。我在等 json {'name': 'foo', 'emailAddress': 'x@x.org'}
并使用架构加载它:
class FooLoad(Schema):
name = fields.Str()
email = fields.Email(data_key='emailAddress', required=True)
我除了加载时的 data_key 会返回一些类似
{'name': 'foo', 'email': 'x@x.org'}
的东西,但我在错误字段中出错:schema_load = FooLoad()
after_load = schema_load.load({'name': 'foo', 'emailAddress': 'x@x.org'})
after_load.errors # return {'email': ['Missing data for required field.']}
但根据来自 marshmallow docs 的示例使用 devDependencies 或 github issue after_load 必须包含类似
{'name': 'foo', 'email': 'x@x.org'}
的数据.我想反序列化传入的日期,其名称与架构属性名称不同(指定 date_key 需要什么),但尝试时出现错误。我如何反序列化具有名称的输入数据,不同于模式属性并在此属性的 data_key 字段中声明?
最佳答案
data_key
在棉花糖 3 中引入。
见 changelog entry :
Backwards-incompatible: Add
data_key
parameter to fields for specifying the key in the input and output data dict. This parameter replaces bothload_from
anddump_to
(#717).
和相关 pull-request .
使用棉花糖 2 时,必须使用
load_from
/dump_to
:class FooLoad(Schema):
name = fields.Str()
email = fields.Email(load_from='emailAddress', dump_to='emailAddress', required=True)
您正在使用棉花糖 2,但正在阅读棉花糖 3 的文档。
请注意,marshmallow 3 包含大量改进并且处于 RC 状态,因此如果您正在开始一个项目,您可以选择 marshmallow 3 并在将来为自己节省一些过渡工作。
关于python - 尝试使用棉花糖使用 data_key 加载数据时出现“丢失数据”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54745134/