dict
object.
Model.dict()
Return data as native dict and list
$ pip install dictify
Let's start with an example note data:
{
"title": "Dictify",
"content": "dictify is easy",
"timestamp": "2021-06-13T05:13:45.326869"
}
The schema condition should be like:
title
str
instancecontent
str
instancetimestamp
from datetime import datetime
from dictify import Model, Field
class Note(Model):
title = Field(required=True)\
.instance(str)\
.verify(lambda value: len(value) <= 300) # [1]
content = Field().instance(str)
timestamp = Field(
required=True,
default=lambda: datetime.utcnow().isoformat())\
.verify(lambda value: datetime.fromisoformat(value))
[1] Field validations can be chained.
note = Note({'title': 'Dictify', 'content': 'dictify is easy'})
Worry free, invalid data can't be assigned at anytime.
# `note` can be used like a dict object.
note.update({"content": "Updated content"})
note["content"] = "Updated again"
# Code below will raise `Model.Error`.
note.update({'title': 0})
note['title'] = 0
Note : Use
try..except
to catch errors if needed.
dict
or JSON
import json
note_dict = dict(note) # Convert to python built-in `dict`
note_json = json.dumps(note) # Convert to JSON string