** I didn't notice it at all when I wrote it, but now it seems that it has moved to schematics
. I will write the schematics
version soon ... maybe. ** **
dictshield
is a library for validating JSON objects.
Since it can be defined by class, it seems to be easy to use because it is similar to the model and form class of django
that I usually use, the document class of mongoengine
, etc., and the code base is compact and the visibility is good. trial. As you follow through the code, it seems that MongoDB and JSON Schema are also taken into consideration.
documents.py
from dictshield.document import Document
from dictshield.fields import StringField, IntField, FloatField, BooleanField, DateTimeField
class SampleDocument(Document):
id = IntField(min_value=0)
name = StringField()
gps_attached = BooleanField()
temperature = FloatField()
created_at = DateTimeField()
Inspecting a JSON object converts the JSON object to dict
and then throws it into the document class.
import json
json_data = '{"id": 1, "name": "foo", "gps_attached": true, "temperature": 23.5, "created_at": "2013-01-01T12:34:56" }'
data = json.loads(json_data)
document = SampleDocument(**data)
document.validate() #True is returned
To use a nested (?) JSON object, use the ʻEmbeddedDocument` class. An example of separating peripheral sensor information.
documents.py
from dictshield.document import Document, EmbeddedDocument
from dictshield.fields import StringField, IntField, FloatField, BooleanField, DateTimeField
from dictshield.fields.compound import EmbeddedDocumentField
class PeripheralEmbeddedDocument(EmbeddedDocument):
gps_attached = BooleanField()
temperature = FloatField()
class SampleDocument(Document):
id = IntField()
name = StringField(max_length=5)
created_at = DateTimeField()
peripheral = EmbeddedDocumentField(PeripheralEmbeddedDocument)
data = {
u'created_at': u'2013-01-01T12:34:56',
u'id': 1,
u'name': u'foo',
u'peripheral': {
u'gps_attached': True,
u'temperature': 23.5
}
}
document = SampleDocument(**data)
document.validate() #True is returned
If validation fails, a ShieldException will be thrown.
data = {
u'created_at': u'2013-01-01T12:34:56',
u'id': 1,
u'name': u'hogheoge', #long
u'peripheral': {
u'gps_attached': True,
u'temperature': 23.5
}
}
document = SampleDocument(**data)
document.validate()
---------------------------------------------------------------------------
ShieldException Traceback (most recent call last)
<ipython-input-76-8d15894a526a> in <module>()
----> 1 document.validate()
/somewhere/lib/python2.7/site-packages/dictshield/document.pyc in validate(self, validate_all)
333 # NB: raising a ShieldDocException in this case would be more
334 # consistent, but existing code might expect ShieldException
--> 335 raise err
336
337 if errs:
ShieldException: String value is too long - name:hogheoge
max_value
and min_value
options of ʻIntField` are not working ...Recommended Posts