Helper classes that encode/decode pynamodb models to/from JSON serializable dict
Project description
pynamodb-encoder
Introduction
pynamodb-encoder
provides helper classes that can convert PynamoDB Model
objects into JSON
serializable dict
. It can also decode such dict
back into those Model
objects. Polymorphic models and attributes are also supported.
Examples
def test_encode_complex_model(encoder: Encoder):
class Pet(DynamicMapAttribute):
cls = DiscriminatorAttribute()
name = UnicodeAttribute()
class Cat(Pet, discriminator="Cat"):
pass
class Dog(Pet, discriminator="Dog"):
pass
class Human(Model):
name = UnicodeAttribute()
pets = ListAttribute(of=Pet)
jon = Human(name="Jon", pets=[Cat(name="Garfield", age=43), Dog(name="Odie")])
assert encoder.encode(jon) == {
"name": "Jon",
"pets": [{"cls": "Cat", "name": "Garfield", "age": 43}, {"cls": "Dog", "name": "Odie"}],
}
def test_decode_complex_model(decoder: Decoder):
class Pet(DynamicMapAttribute):
cls = DiscriminatorAttribute()
class Cat(Pet, discriminator="Cat"):
name = UnicodeAttribute()
class Dog(Pet, discriminator="Dog"):
breed = UnicodeAttribute()
class Human(Model):
name = UnicodeAttribute()
age = NumberAttribute()
pets = ListAttribute(of=Pet)
jon = decoder.decode(
Human,
{
"name": "Jon",
"age": 70,
"pets": [{"cls": "Cat", "name": "Garfield"}, {"cls": "Dog", "breed": "Terrier"}],
},
)
assert jon.name == "Jon"
assert jon.age == 70
assert isinstance(jon.pets, list)
assert len(jon.pets) == 2
assert isinstance(jon.pets[0], Cat)
assert jon.pets[0].name == "Garfield"
assert isinstance(jon.pets[1], Dog)
assert jon.pets[1].breed == "Terrier"
More examples can be found in encoder_test.py and decoder_test.py
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
Built Distribution
File details
Details for the file pynamodb_encoder-0.2.0.tar.gz
.
File metadata
- Download URL: pynamodb_encoder-0.2.0.tar.gz
- Upload date:
- Size: 4.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.2 CPython/3.12.3 Linux/6.5.0-1018-azure
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 40d5b8b465ea51d3818eef7a8e085634b31b72edbb8cb6d9680e3c412945a2f6 |
|
MD5 | 9c68a05782c33d492671cca1d93779ea |
|
BLAKE2b-256 | dfe3d3d8f91ce486da2a38995a5e0e6d8551c99ca6ec72673d5f22231da671e5 |
File details
Details for the file pynamodb_encoder-0.2.0-py3-none-any.whl
.
File metadata
- Download URL: pynamodb_encoder-0.2.0-py3-none-any.whl
- Upload date:
- Size: 6.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.2 CPython/3.12.3 Linux/6.5.0-1018-azure
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5b02f07586df2ff5261a6b3e8958f6a13112a68cc49ce783982c3ebcc01094fa |
|
MD5 | 1a05ad2ccd584e5a9a9508986185d901 |
|
BLAKE2b-256 | 9ddcfc293de0cddf24e8a71f7c08f6378f1cf0ab8c87955d9445606e539cb2ca |