Marshmallow反序列化时如何映射Schema属性为目标键(处理from保留字)
解决Marshmallow中使用Python保留字"from"作为字段的问题
你可以通过Marshmallow的post_load钩子函数,在反序列化完成后修改字典的键,实现将内部字段名_from替换为目标键from:
from marshmallow import Schema, fields, post_load class TestSchema(Schema): _from = fields.Str( required=False, missing='', data_key='from' ) @post_load def adjust_from_key(self, data, **kwargs): # 将内部字段名"_from"替换为目标键"from" if '_from' in data: data['from'] = data.pop('_from') return data
效果验证
当你调用load方法处理输入数据时:
schema = TestSchema() result = schema.load({"from": "example@test.com"}) print(result) # 输出: {"from": "example@test.com"}
如果需要同时处理序列化(将字典中的from转换为符合Schema定义的输出),可以再添加post_dump钩子:
@post_dump def revert_from_key(self, data, **kwargs): if 'from' in data: data['_from'] = data.pop('from') return data
这样无论反序列化还是序列化,都能在外部数据和内部处理之间完成键的映射,同时规避Python保留字的限制。
内容的提问来源于stack exchange,提问作者Roman Yakubovich
相关产品推荐
相关产品推荐

