Open
Description
Base on the documentation that validation does not occur on serialisation anymore https://marshmallow.readthedocs.io/en/stable/upgrading.html.
There is example how to workaround. However this alternative is flawed since it does not work if you use data_key on created_at (like camlcase).
Another case that does not work is if you actually pass a correct value (like current datetime).
Is there any alternative that takes data_key into account?
I think documentation would need to be updated to reflect that use case.
from marshmallow import Schema, fields, ValidationError
invalid_data = dict(created_at="invalid")
class WidgetSchema(Schema):
created_at = fields.DateTime(data_key='createdAt')
# 2.x
# WidgetSchema(strict=True).dump(invalid_data)
# marshmallow.exceptions.ValidationError: {'created_at': ['"invalid" cannot be formatted as a datetime.']}
# 3.x
# WidgetSchema().dump(invalid_data)
# AttributeError: 'str' object has no attribute 'isoformat'
# Instead, validate before dumping
schema = WidgetSchema()
try:
widget = schema.load(invalid_data)
except ValidationError as e:
print("handle errors... {}".format(e.messages))
else:
dumped = schema.dump(widget)
Another case that does not work:
invalid_data = dict(created_at=datetime.datetime.now())