Skip to content

ypankovych/pankoff

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Pankoff

Downloads Documentation Status PyPI pyversions Maintenance MIT License PyPi status PyPI version fury.io PyPI implementation PRs Welcome

Lightweight, flexible, easy to use validation tool. Pure Python, no dependencies.

Validate, mutate, serialize and deserialize with lots of magic.

pip install --user pankoff

Read full documentation here.

$ cat data.json
{
    "name": "Yaroslav",
    "salary": "100 USD",
    "kind": 1
}
from pankoff.base import Container
from pankoff.combinator import combine
from pankoff.exceptions import ValidationError
from pankoff.magic import autoinit
from pankoff.validators import String, BaseValidator, Number

kinds = {
    1: "Good person",
    2: "Bad person"
}


class Salary(BaseValidator):

    def __setup__(self, amount, currency):
        self.amount = amount
        self.currency = currency

    def mutate(self, instance, value):
        return f"{instance.name} salary is: {value}"

    def validate(self, instance, value):
        amount, currency = value.split()
        if int(amount) != self.amount or currency != self.currency:
            raise ValidationError(f"Wrong data in field: `{self.field_name}`")


class KindMutator(BaseValidator):

    def validate(self, instance, value):
        if value not in kinds:
            raise ValidationError(f"Person kind should be in {kinds.keys()}")

    def mutate(self, instance, value):
        return kinds[value]


@autoinit
class Person(Container):
    name = String()
    salary = Salary(amount=100, currency="USD")
    kind = combine(Number, KindMutator)()


if __name__ == "__main__":
    Person.from_path("data.json").to_path("mutated_data.json", indent=4)
$ cat mutated_data.json
{
    "name": "Yaroslav",
    "salary": "Yaroslav salary is: 100 USD",
    "kind": "Good person"
}