gopal_hegde
gopal_hegde

Reputation: 53

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. Is there any way to pass custom arguments when instantiating a marshamallow Schema? Also, how do I pass custom arguments to the pre_load method of the schema? 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)

Upvotes: 2

Views: 4150

Answers (1)

Jinay Shah
Jinay Shah

Reputation: 51

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.

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
)

Upvotes: 5

Related Questions