[英]Passing custom arguments to marshmallow Schema and Pre-processing methods
I am a new user of marshamallow and trying to use the Schema for validating flexible JSON/dict records in Python.我是marshamallow的新用户,并尝试使用 Schema 来验证 Python 中的灵活 JSON/dict 记录。 Is there any way to pass custom arguments when instantiating a marshamallow Schema?实例化marshamallow Schema 时,有什么方法可以通过自定义 arguments 吗? Also, how do I pass custom arguments to the pre_load method of the schema?另外,如何将自定义 arguments 传递给架构的 pre_load 方法? My requirement is something like below我的要求如下
from marshmallow import Schema, fields, post_load, EXCLUDE, validate, \
validates, pre_load
class UserSchema(Schema):
name = fields.Str()
joined_on = fields.AwareDateTime()
@pre_load
def sanitize(self, data, **kwargs):
tzinfo = kwargs.get('tzinfo')
data['joined_on'] = tzinfo.localize(data['joined_on'])
return data
schema = UserSchema()
user = schema.load({"name": "Tim", "joined_on": datetime.datetime(2019, 10, 23)}, tzinfo=pytz.utc)
Custom arguments cannot be passed directly to the marshmallow load
function, but they can be passed as key-value pairs to data argument of the load
function, in conjunction with pass_original=True
argument of post_load
decorator.自定义 arguments 不能直接传递给棉花糖load
function,但它们可以作为键值对传递给load
function 的数据参数,与post_load
装饰器的pass_original=True
一起使用。
Solution:解决方案:
import pytz
from marshmallow import (
fields,
post_load,
EXCLUDE,
Schema,
)
class UserSchema(Schema):
name = fields.Str()
joined_on = fields.AwareDateTime(required=True)
@post_load(pass_original=True)
def sanitize(self, data, original_data, **_):
tzinfo = original_data.get('tzinfo', pytz.utc)
data['joined_on'] = tzinfo.localize(data['joined_on'])
return data
schema = UserSchema()
user = schema.load(
{
"name": "Tim",
"joined_on": datetime.datetime(2019, 10, 23),
"tzinfo"=pytz.timezone("Asia/Kolkata")
},
unknown=EXCLUDE
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.