Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validation does not occur on serialization documentation issue #2189

Open
matejsp opened this issue Sep 18, 2023 · 2 comments
Open

Validation does not occur on serialization documentation issue #2189

matejsp opened this issue Sep 18, 2023 · 2 comments
Labels

Comments

@matejsp
Copy link

matejsp commented Sep 18, 2023

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())
@matejsp matejsp changed the title Validation does not occur on serialization Validation does not occur on serialization documentation issue Sep 18, 2023
@lafrech lafrech added the docs label Oct 1, 2023
@deckar01
Copy link
Member

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

@matejsp
Copy link
Author

matejsp commented Nov 22, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants