Skip to content
This repository has been archived by the owner on Jan 28, 2022. It is now read-only.

pre_load and post_load decorators

Sergey Vilgelm edited this page Mar 19, 2018 · 1 revision
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.

Clone this wiki locally