Installation#
Available from PyPI:
pip install serious
Models In Short#
Models are the central part of the serious API:
from serious import JsonModel
model = JsonModel(Stock)
model.load('{"name": "AAPL", "price": "139.38"}')
You encode, decode and validate the dataclasses via model methods.
Model constructor allows to change the specifics of working with particular dataclass,
e.g. JsonModel(Job, allow_missing=True)
will set None
to fields marked Optional
in Job
dataclass
when they are missing from loaded JSON.
There are two types of Model as of now:
For more refer to models docs.
Simple Serialization#
Having a dataclass:
from dataclasses import dataclass
@dataclass
class Person:
name: str
Create an instance of JsonModel
:
from serious.json import JsonModel
model = JsonModel(Person)
And use its dump/load methods:
person = Person('Albert Einstein')
model.dump(person) # {"name": "Albert Einstein"}
Basic Validation#
To validate instance of a dataclass upon load — add a __validate__
method to it:
from dataclasses import dataclass
from typing import List
from serious import DictModel, ValidationError
@dataclass
class Order:
lines: List[str]
def __validate__(self):
if len(self.lines) == 0:
raise ValidationError('Order cannot be empty')
model = DictModel(Order)
Now passing an invalid object for decoding to this model will result in ValidationError
:
try:
model.load({'lines': []})
except ValidationError as e:
print(str(e)) # Order cannot be empty