pre_load and post_load decorators - sv-tools/marshmallow-objects GitHub Wiki
import marshmallow_objects as marshmallow
class EmailModel(marshmallow.Model):
email = marshmallow.fields.Str()
@marshmallow.pre_load(pass_many=True)
def remove_envelope(self, data, many):
assert isinstance(data, dict)
namespace = 'emails' if many else 'email'
return data[namespace]
@marshmallow.post_load
def lowerstrip_email(self, item):
assert isinstance(item, marshmallow.Model)
item.email = item.email.lower().strip()
return item
print('\n'.join(m.email for m in EmailModel.load(
{'emails': [{'email': ' [email protected] '},
{'email': ' [email protected]'}]
}, many=True)))
# [email protected]
# [email protected]
Note: a post_load function receives an object of the Model class, but a pre_load function works with raw data.