APIFairy
APIFairy copied to clipboard
Problem with loading datetime in Marshmallow Schema.
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.
Have you seen how I do this? https://github.com/miguelgrinberg/microblog-api/blob/main/api/users.py#L73.
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.
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.