Skip to main content
Join the official 2019 Python Developers SurveyStart the survey!

Serialize and deserialize python object to JSON and back

Project description

SoKu

Codacy Badge Codacy Badge

SoKu is small library for serialize and deserialize python object to JSON and back. This library is useful for conversation between micro services, see example. It can to serialize from object and back, validate when deserialize and use custom deserializer and serializer.

Installation

pip install soku

Example

from datetime import datetime
from dataclasses import dataclass
from soku import Class, Attribute


def is_int(_, value):  # validator must be callable and return bool or raise exception
    return isinstance(value, int)


def timestamp_to_date(value):
    return datetime.fromtimestamp(value)


def date_to_timestamp(value):
    return int(value.timestamp())


@dataclass
class FullName(Class):
    first_name: str = Attribute(key='firstName')
    last_name: str = Attribute(key='lastName')

    def full_name(self):
        return f'{self.first_name} {self.last_name}'


@dataclass
class Person(Class):
    id: int = Attribute(validate=is_int)
    full_name: FullName = Attribute(key='fullName', attach=FullName)


@dataclass
class User(Person):
    birthday: datetime = Attribute(deserialize=timestamp_to_date, serialize=date_to_timestamp)


if __name__ == '__main__':
    # create instance and serialize
    full_name = FullName('John', 'Smith')
    user = User(12345, full_name, datetime.fromtimestamp(1193875200))
    print(user.serialize())  #  {'id': 12345, 'birthday': 1193875200, 'fullName': {'firstName': 'John', 'lastName': 'Smith'}}


    # deserialize and serialize
    user = User.deserialize({'id': 12345, 'birthday': 1193875200, 'fullName': {'firstName': 'John', 'lastName': 'Smith'}})
    print(user.full_name.full_name())  # John Smith
    print(user.serialize())  # {'id': 12345, 'birthday': 1193875200, 'fullName': {'firstName': 'John', 'lastName': 'Smith'}}

    # validate
    try:
        User.deserialize({'id': '12345', 'birthday': 1193875200, 'fullName': {'firstName': 'John', 'lastName': 'Smith'}})
    except ValueError as exc:
        print(exc)  # Key id validation error.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for soku, version 2.0.3
Filename, size File type Python version Upload date Hashes
Filename, size soku-2.0.3-py3-none-any.whl (16.1 kB) File type Wheel Python version py3 Upload date Hashes View hashes
Filename, size soku-2.0.3.tar.gz (2.5 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page