DB: MySQL
Im trying to come up with an elegant way to validate incoming JSON post data (this is an API accepting JSON, no FORMS) either before or after it is used to create a new SQLAlchemy model (before database insert/update).
A) I have seen the @validates decorator, but for me that fails in two ways:
- It does not handle validating non-nullable fields since it is only initiated when data is changed
- All documentation shows throwing errors, and I would much rather know what all the errors are on a model, so I could respond back with the error json (ie model.errors)
B) I have looked into Marshamallow for validation/serialization - and although it seems like a potential, it seems like a lot of overhead for something I feel should be more closely connected with the model
C) Flask-Inputs with their json attribute seemed like a middle ground, but I can not seem to get it to work with nested json, and also wonder how I would break up the multiple entries (ie multiple car objects coming in)
D) Ive also looked at using WTF-Forms (see comments). This works, and outside not being able to get Flask-Inputs to work as wanted. This does seem like the most promising/simple -- but it does feel weird to be building these form objects with all their overhead just to use their validators.
Im really wondering if I am going about this the whole wrong way, in pseudo/python code this is my ideal workkflow:
json_data = request.get_json()
for each car_data in json_data:
car = Car(**car_data)
if car.is_valid(): ## this would be a nice model integrity check
session.add(car)
session.commit(car)
Im coming from a Rails world where I could ask the model things, such as (loose naming here, its been a bit)
- .is_dirty? -- is the data still the same as last save
- .is_valid? -- does the model pass integrity checks
- .is_saved? --- is the model persisted
- .error -- provides a dict of errors field : {key: error}
etc ... again, maybe Im just looking at the SQLAlchemy paradigm offset or something, but any guidance here would be amazing!