pynamodb与marshmallow(de)序列化库的集成
marshmallow-pynamodb的Python项目详细描述
PynamoDB与marshmallow(反)序列化库集成。
安装
来自PYPI:
$ pip install marshmallow-pynamodb
来自github:
$ pip install git+https://github.com/mathewmarcus/marshmallow-pynamodb#egg=marshmallow_pynamodb
申报您的型号
frompynamodb.modelsimportModelfrompynamodb.attributesimportUnicodeAttributeclassUser(Model):classMeta:table_name="user"email=UnicodeAttribute(null=True)first_name=UnicodeAttribute(range_key=True)last_name=UnicodeAttribute(hash_key=True)
生成棉花糖架构
frommarshmallow_pynamodbimportModelSchemaclassUserSchema(ModelSchema):classMeta:model=Useruser_schema=UserSchema()
(反)序列化数据
user=User(last_name="Smith",first_name="John")user_schema.dump(user).data# {u'first_name': u'John', u'last_name': u'Smith', u'email': None}user_schema.load({"last_name":"Smith","first_name":"John"}).data# user<Smith>
嵌套模型?没问题
frommarshmallow_pynamodb.schemaimportModelSchemafrompynamodb.modelsimportModelfrompynamodb.attributesimportListAttribute,MapAttribute,NumberAttribute,UnicodeAttributeclassLocation(MapAttribute):latitude=NumberAttribute()longitude=NumberAttribute()name=UnicodeAttribute()classPerson(MapAttribute):firstName=UnicodeAttribute()lastName=UnicodeAttribute()age=NumberAttribute()classOfficeEmployeeMap(MapAttribute):office_employee_id=NumberAttribute()person=Person()office_location=Location()classOffice(Model):classMeta:table_name='OfficeModel'office_id=NumberAttribute(hash_key=True)address=Location()employees=ListAttribute(of=OfficeEmployeeMap)classOfficeSchema(ModelSchema):classMeta:model=OfficeOfficeSchema().load({'office_id':789,'address':{'latitude':6.98454,'longitude':172.38832,'name':'some_location'},'employees':[{'office_employee_id':123,'person':{'firstName':'John','lastName':'Smith','age':45},'office_location':{'latitude':-24.0853,'longitude':144.87660,'name':'other_location'}},{'office_employee_id':456,'person':{'firstName':'Jane','lastName':'Doe','age':33},'office_location':{'latitude':-20.57989,'longitude':92.30463,'name':'yal'}}]}).data# Office<789>
许可证
麻省理工学院许可有关详细信息,请参阅捆绑的LICENSE文件。