A library designed primarily for serializing objects using type checking and resolvers.
Project description
porcupine-python
Hi. I am a fucking porcupine 🦔. I am here to serialize your responses 💪.
Usage
porcupine-python is used for type and nested serialization of any objects with attributes into dictionaries.
Simple usage
First we need to create some simple class:
class User(object):
def __init__(self, name=None, surname=None, age=None):
self.name = name
self.surname = surname
self.age = age
Second we create serializer for this type of class:
from porcupine.base import Serializer
class UserSerializer(Serializer):
name: str
surname: str
age: int = None
Final usage with different created instances looks like this:
# User instance with all attributes
user = User('foo', 'bar', 23)
dictionary = UserSerializer(user).dict()
# dictionary: {'name': 'foo', 'surname': 'bar', 'age': 23}
# User instance with only required attributes
user = User('foo', 'bar')
dictionary = UserSerializer(user).dict()
# dictionary: {'name': 'foo', 'surname': 'bar', 'age': None}
# User instance with all None attributes
user = User()
dictionary = UserSerializer(user).dict()
# raised ValidationError
Usage of resolvers
First we need to create some class which instances will be resolved:
class User(object):
def __init__(self, name=None, surname=None, age=None):
self.name = name
self.surname = surname
Serializer for that class:
from porcupine.base import Serializer
class UserSerializer(Serializer):
name: str = None
surname: str = None
full_name: str = None
@staticmethod
def resolve_full_name(data):
fullname = None
if data.name and data.surname:
fullname = f'{data.name} {data.surname}'
elif data.name:
fullname = data.name
elif data.surname:
fullname = data.surname
return fullname
Serialized user instance:
user = User('foo', 'bar')
dictionary = UserSerializer(user).dict()
# dictionary: {'name': 'foo', 'surname': 'bar', 'full_name': 'foo bar'}
Made with ❤ by Adam Žúrek & BACKBONE s.r.o.
0.1.0 : 2020-05-26
- Initial release
0.2.0 : 2020-06-27
- Fixed Expected type 'Dict[str, Any]' warning when calling BaseSerializer
- Implemented test for nested objects.
0.3.0 : 2020-11-27
- 🦦 Implemented possibility to add custom arguments to serializers.
- 🦦 Pydantic version requirement changed from
1.4.*
to1.7.*
.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
porcupine-python-0.3.0.tar.gz
(3.4 kB
view hashes)
Built Distribution
Close
Hashes for porcupine_python-0.3.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0bddb5684560786f1eb64bebbf65f5052921f5197ca2336defc6ce650d1eda24 |
|
MD5 | 0e16a290ed45cd2e50207af161765602 |
|
BLAKE2b-256 | b198ede2b531757df6a7d607d1731292d925414f45b678c4991c8b3f9d39ed2d |