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.1.1.tar.gz
.
File metadata
- Download URL: pynamodb-encoder-0.1.1.tar.gz
- Upload date:
- Size: 4.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.1.12 CPython/3.10.0 Linux/5.11.0-1022-azure
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | f491233396418eedf2cc7694859d245d645d6562cffea7cc15bd2230e2ed707c |
|
MD5 | dab42d336f33d60d0a5904cd045d48bc |
|
BLAKE2b-256 | 08bc86f2d5f964e6f9d7fcf3a2c91b08fa5df32e649e2116f8c34f44d8e2f483 |
File details
Details for the file pynamodb_encoder-0.1.1-py3-none-any.whl
.
File metadata
- Download URL: pynamodb_encoder-0.1.1-py3-none-any.whl
- Upload date:
- Size: 6.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.1.12 CPython/3.10.0 Linux/5.11.0-1022-azure
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5039c2a85ade4004eaa363fb85d703d343cccd9d02b34019655cc80989312047 |
|
MD5 | 2f34994c5b8c839fa03280d65bb8a30e |
|
BLAKE2b-256 | 1db400ea3fd0de8b953ede7399ec5308244cefa5b8d5d66a661aebb418bd1d35 |