marshmallow-code/marshmallow

Validation does not occur on serialization documentation issue

matejsp opened this issue · 2 comments

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())

If you can't guarantee that data being dump()ed is valid, it needs to be load()ed.

https://marshmallow.readthedocs.io/en/stable/quickstart.html#deserializing-objects-loading

Yes this is possible but is not the "alternative" according to docs. Better way would be do to validate() instead of load().

It says validate before dumping to get the same behaviour.
Perhaps docs should be changed to reflect this.