All Projects → freelancer → pavlova

freelancer / pavlova

Licence: LGPL-3.0, GPL-3.0 licenses found Licenses found LGPL-3.0 COPYING.LESSER GPL-3.0 LICENSE
A python deserialisation library built on top of dataclasses

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to pavlova

dataclasses-jsonschema
JSON schema generation from dataclasses
Stars: ✭ 145 (+353.13%)
Mutual labels:  deserialization, dataclasses
dataconf
Simple dataclasses configuration management for Python with hocon/json/yaml/properties/env-vars/dict support.
Stars: ✭ 40 (+25%)
Mutual labels:  deserialization, dataclasses
Orjson
Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy
Stars: ✭ 2,595 (+8009.38%)
Mutual labels:  deserialization, dataclasses
Dart Json Mapper
Serialize / Deserialize Dart Objects to / from JSON
Stars: ✭ 206 (+543.75%)
Mutual labels:  deserialization
Schematics
Project documentation: https://schematics.readthedocs.io/en/latest/
Stars: ✭ 2,461 (+7590.63%)
Mutual labels:  deserialization
sqlathanor
Serialization / De-serialization support for the SQLAlchemy Declarative ORM
Stars: ✭ 105 (+228.13%)
Mutual labels:  deserialization
aio-openapi
A python module for building OpenAPI compliant asynchronous Rest Servers. Auto documentation, serialization and validation in the same unified API.
Stars: ✭ 27 (-15.62%)
Mutual labels:  dataclasses
Drf Typed Views
Use type annotations to validate/deserialize request parameters in Dango REST Framework.
Stars: ✭ 181 (+465.63%)
Mutual labels:  deserialization
argparse dataclass
Declarative CLIs with argparse and dataclasses
Stars: ✭ 30 (-6.25%)
Mutual labels:  dataclasses
avro-serde-php
Avro Serialisation/Deserialisation (SerDe) library for PHP 7.3+ & 8.0 with a Symfony Serializer integration
Stars: ✭ 43 (+34.38%)
Mutual labels:  deserialization
jsonargparse
Implement minimal boilerplate CLIs derived from type hints and parse from command line, config files and environment variables
Stars: ✭ 168 (+425%)
Mutual labels:  dataclasses
Jsonapi Rb
Efficiently produce and consume JSON API documents.
Stars: ✭ 219 (+584.38%)
Mutual labels:  deserialization
marshmallow-validators
Use 3rd-party validators (e.g. from WTForms and colander) with marshmallow
Stars: ✭ 24 (-25%)
Mutual labels:  deserialization
Mashumaro
Fast and well tested serialization framework on top of dataclasses
Stars: ✭ 208 (+550%)
Mutual labels:  deserialization
rtoml
A fast TOML library for python implemented in rust.
Stars: ✭ 214 (+568.75%)
Mutual labels:  deserialization
Marshmallow Jsonapi
JSON API 1.0 (https://jsonapi.org/) formatting with marshmallow
Stars: ✭ 203 (+534.38%)
Mutual labels:  deserialization
Anamnesis.jl
Fancy memoizing for expensive functions in Julia.
Stars: ✭ 18 (-43.75%)
Mutual labels:  deserialization
pagser
Pagser is a simple, extensible, configurable parse and deserialize html page to struct based on goquery and struct tags for golang crawler
Stars: ✭ 82 (+156.25%)
Mutual labels:  deserialization
Python37Tutorial
Python 3.7 技術手冊資料
Stars: ✭ 15 (-53.12%)
Mutual labels:  python37
hydra-zen
Pythonic functions for creating and enhancing Hydra applications
Stars: ✭ 165 (+415.63%)
Mutual labels:  dataclasses

pavlova: simplified deserialization using dataclasses

pavlova is a library that assists in mapping an unknown input into a dataclass.

from datetime import datetime
from dataclasses import dataclass

from pavlova import Pavlova


@dataclass
class Input:
    id: int
    name: str
    date: datetime


Pavlova().from_mapping({
    'id': 10,
    'name': 100
    'date': '2018-08-10',
}, Input)
# Input(id=10, name='100', date=datetime.datetime(2018, 8, 10, 0, 0))

Pavlova was born out of frustration with the lack of typing support for existing deserialization libraries. With the introduction of dataclasses in Python 3.7, they seemed like the perfect use for defining a deserialization schema.

Supported functionality

Parsing of booleans, datetimes, floats, ints, strings, decimals, dictionaries, enums, lists are currently supported.

There are more parsers to come, however to implement your own custom parser, simply implement PavlovaParser in pavlova.parsers, and register it with the Pavlova object with the register_parser method.

Installation

pip install pavlova

Usage with Flask

from dataclasses import dataclass, asdict

from flask import Flask, jsonify
from pavlova.flask import FlaskPavlova

pavlova = FlaskPavlova()
app = Flask(__name__)

@dataclass
class SampleInput:
    id: int
    name: str

@app.route('/post', methods=['POST'])
@pavlova.use(SampleInput)
def data(data: SampleInput):
    data.id = data.id * len(data.name)
    return jsonify(asdict(data))


app.run()

Adding Custom Types

There are a couple of different ways to implement new types for parsing in pavlova. In general, the process is to add a parser a specific type. For validation you should raise a TypeError or ValueError.

The first one, is creating a new type that extends an existing base type. Here is an example on how to implement an Email type, which is a string but performs validation.

from pavlova import Pavlova
from pavlova.parsers import GenericParser

class Email(str):
    def __new__(cls, input_value: typing.Any) -> str:
        if isinstance(input_value, str):
            if '@' in input_value:
                return str(input_value)
            raise ValueError()
        raise TypeError()

pavlova = Pavlova()
pavlova.register_parser(Email, GenericParser(pavlova, Email))

Another way, is to implement your own pavlova parser, rather than using your the built in GenericParser parser.

import datetime
from typing import Any, Tuple

import dateparser
from pavlova import Pavlova
from pavlova.parsers import PavlovaParser

class DatetimeParser(PavlovaParser[datetime.datetime]):
    "Parses a datetime"

    def parse_input(self,
                    input_value: Any,
                    field_type: Type,
                    path: Tuple[str, ...]) -> datetime.datetime:
        return dateparser.parse(input_value)

pavlova = Pavlova()
pavlova.register_parser(datetime.DateTime, DatetimeParser(pavlova))

Requirements

Pavlova is only supported on Python 3.6 and higher. With Python 3.6, it will install the dataclasses module. With Python 3.7 and higher, it will use the built-in dataclasses module.

License

GNU LGPLv3. Please see LICENSE and COPYING.LESSER.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].