python marshmallow 缺少选项自定义函数保持输出相同的值

python marshmallow missing option custom function keep output the same value

python 版本 3.7,棉花糖 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)

我发现加载的数据都具有相同的 created_datetime 而我希望它们不同。 missing和default只能是固定值是这样吗?

您需要提供一个不接受参数的可调用对象来生成动态 default/missing 值。例如,使用上面的代码:

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'}
"""