Skip to main content

Helper classes that encode/decode pynamodb models to/from JSON serializable dict

Project description

pynamodb-encoder

Build CodeQL codecov Maintainability PyPI version PyPI Supported Python Versions

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

pynamodb_encoder-0.2.0.tar.gz (4.1 kB view hashes)

Uploaded Source

Built Distribution

pynamodb_encoder-0.2.0-py3-none-any.whl (6.2 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page