Created
March 7, 2018 02:31
-
-
Save toshke/42e286edc1938eb971a6fe02343747e0 to your computer and use it in GitHub Desktop.
PynamoDB serialize models to json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pynamodb.models import Model | |
from pynamodb.attributes import UnicodeAttribute, ListAttribute, MapAttribute | |
import os | |
import json | |
class BaseModel(Model): | |
def to_dict(self): | |
rval = {} | |
for key in self.attribute_values: | |
rval[key] = self.__getattribute__(key) | |
return rval | |
class AddressModel(MapAttribute): | |
street = UnicodeAttribute() | |
city = UnicodeAttribute() | |
class Person(BaseModel): | |
class Meta: | |
table_name = os.environ.get('PERSONS_TABLE', 'persons') | |
id = UnicodeAttribute(hash_key=True) | |
addresses = ListAttribute(of=AddressModel) | |
if not Person.exists(): | |
Person.create_table(read_capacity_units=1, write_capacity_units=1, wait=True) | |
p = Person(hash_key='1', range_key=None, addresses=[{'street': 'JohnSt', 'city': 'New York, NYC'}]) | |
print(json.dumps(p.to_dict(), indent=2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment