将 JSON "反序列化"为 sqlalchemy 模型



我正在使用sqlalchemy将一些RESTful api调用存储到关系数据库中,我正在寻找一种方法来"反序列化"或Python化一些或所有传入字段,例如,我可能有一个类似的json对象

{
'id': 1,
'created_at': '2021-05-27T03:22:38Z',
'count': '3'
}

我想要一种";自动地";反序列化数据,类似于djangorestframework序列化程序在";created_ at";可以定义为日期时间字段,您可以选择将"count"强制转换为整数,并运行类似的操作

...setup
# get the json from before as a dict 
item = client.get_item()
# somehow serialize here
session = Session()
item_model = Item(**item_data[0])
session.add(item_model)
session.commit()

https://www.django-rest-framework.org/api-guide/serializers/

您有多个众所周知的模块来执行序列化(独立于任何框架(:

棉花糖:https://marshmallow.readthedocs.io/en/stable/打字系统(由DRF创建者提供(:https://github.com/encode/typesystem

如果您的用例很简单,您也可以基于DRF序列化程序代码创建自己的序列化程序,或者只查找执行验证/转换的dict字段。

最新更新