Flask-Marshmallow validation failed on DateTime when value is DateTime

1.8k views Asked by At

I have the following data:

data={
     'last_visit':datetime.datetime(2020, 9, 30, 11, 12, 24, 512347)
}

The schema is based on the model:

class ModelSchema(db_schema.SQLAlchemyAutoSchema):
    class Meta:
        model = UserModel

and the model itself:

class UserModel(db.Model, AllFeaturesMixin):
    last_visit= db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

When I do validation, I have an error:

> schema.validate(self.data)
> {'last_visit': ['Not a valid datetime.']}

Not sure why.

1

There are 1 answers

0
Lucas Scott On

validate() should be called on the raw data from flask.request.get_json() or equivalent. What you are looking for is the raw results of deserialization from something like json.loads(). With this raw dictionary last_visit is still a string, and is what marshmallow DateTime field is expecting (a formatted datetime string).

Below is a basic example:

import datetime
import json
import flask
import marshmallow as ma
from datetime import timezone

app = flask.Flask(__name__)
default_headers = {"Content-Type": "application/json"}


class ModelSchema(ma.Schema):
    last_visit = ma.fields.DateTime()


@app.route("/last_visit", methods=["POST"])
def get_last_visit():
    schema = ModelSchema()
    data = flask.request.get_json()

    errors = schema.validate(data)
    if errors:
        return errors, 400, default_headers

    last_visit_data = schema.load(data)
    last_visit_data["last_visit"] = datetime.datetime.now(tz=timezone.utc)
    last_visit_response_data = schema.dumps(last_visit_data)

    return last_visit_response_data, 200, default_headers