Search code examples
pythonmarshmallow

python marshmallow missing option custom function keep output the same value


python version 3.7, marshmallow 3.1.1

class userSchema(Schema):
    created_datetime = fields.Str(required=False, missing=str(datetime.datetime.now()))
    name = fields.Str()

for i in range(3):
    time.sleep(5)
    user_data = {"name": "test"}
    test_load = userSchema.load(user_data)
    print(test_load)

I found the loaded data are all with the same created_datetime whereas I expect them to be different. Is this the case that missing and default can only be a fixed value?


Solution

  • You need to provide a callable that accepts no arguments to generate a dynamic default/missing value. For example, using your code above:

    from marshmallow import Schema, feilds
    from datetime import datetime, timezone
    
    
    def datetime_str_now():
        """ create timezone aware datetime """
        return datetime.now(
            tz=timezone.utc  # remove this if you don't need timezone aware dates
        ).isoformat()
    
    class userSchema(Schema):
        created_datetime = fields.Str(
            required=False,
            missing=datetime_str_now
        )
        name = fields.Str()
    
    for i in range(3):
        time.sleep(5)
        user_data = {"name": "test"}
        test_load = userSchema().load(user_data)
        print(test_load)
    
    """ Outputs:
    {'created_datetime': '2020-10-07T09:08:00.847929+00:00', 'name': 'test'}
    {'created_datetime': '2020-10-07T09:08:01.851066+00:00', 'name': 'test'}
    {'created_datetime': '2020-10-07T09:08:02.854573+00:00', 'name': 'test'}
    """