Django / python checks JSON

What is the best way to validate JSON data in Django / python.

Is it better to create a bunch of classes, such as Django FormMixin classes, that can check for passed data / parameters?

What is the best way to do this? Are there any existing applications that I can use?

I would like to take JSON data and perform some actions / updates on model instances. The data that I accept is not created by the user, that is, they are id and flags (without text), so I do not want to use Forms.

+4
source share
3 answers

I just create an instance of the model object from json data and call full_clean () for the model: https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean

m = myModel(**jsondata) m.full_clean() 
+7
source

validictory validate json on json-schema. It works. Of course, now you need to define your schema in json, which may be a little for what you want to do, but it does have a place.

+4
source

I would recommend a python library called DictShield for this https://github.com/j2labs/dictshield

DictShield is a database agnostic modeling system. This makes it easy to model, validate and modify data.

There is even a sample for checking JSON:

User input validation

Let's say we get this JSON string from the user.

{"bio": "Python, Erlang and guitars!", "secret": "e8b5d682452313a6142c10b045a9a135", "name": "J2D2"}

We could write server code that looks like this:

 json_string = request.get_arg('data') user_input = json.loads(json_string) user.validate(**user_input) 
+1
source

Source: https://habr.com/ru/post/1392504/


All Articles