miguelgrinberg / APIFairy

A minimalistic API framework built on top of Flask, Marshmallow and friends.
MIT License
320 stars 29 forks source link

Problem with loading datetime in Marshmallow Schema. #87

Open aderbas opened 4 weeks ago

aderbas commented 4 weeks ago

I'm trying to load the parameters coming from the PUT request into the schema.

# schema.py
class ProjectMergeSchema(ma.Schema):
        id = ma.Integer()
        date_time_created = ma.DateTime()
# views.py
@blueprint.route('/', methods=['PUT'])
@response(project_schema)
@body(merge_schema)
def update(args, service: ProjectService):
    """Update."""
    return service.update(merge_schema.load(args))

input payload:

print(args)
# {'id': 14, 'date_time_created': datetime.datetime(2024, 6, 4, 11, 47, 4)}

The problem here is that the date_time_created field in the args object is already converted to datetime and marshmallow gives error:

marshmallow.exceptions.ValidationError: {'date_time_created': ['Not a valid datetime.']}

Is there any way for the date parameter to remain as a string? I'm using request.json to get around the problem but pylint complains about an unused variable (args in the method).

I do not know if i was clear.

miguelgrinberg commented 4 weeks ago

Have you seen how I do this? https://github.com/miguelgrinberg/microblog-api/blob/main/api/users.py#L73.

aderbas commented 4 weeks ago

The problem is in the values ​​that come from the args that are injected into the method def update(args) I didn't want, for each view, to treat date fields.. When it is a date field it is already converted to python datetime. When serializing within the schema, it gives an error.

miguelgrinberg commented 4 weeks ago

The args that the endpoint receives are already parsed. You are trying to parse them again and that is why you get the error. Once again, have a look at my code, I do not have any issues with datetimes in updates, at least I don't think I do.