“反序列化” JSON 到 sqlalchemy 模型
我正在使用 sqlalchemy 将一些 RESTful api 调用存储到关系数据库中,并且我正在寻找一种“反序列化”或 pythonify 部分或全部传入字段的方法,例如我可能有一个像这样的 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/
I'm storing some RESTful api calls into a relational database using sqlalchemy, and I'm looking for a way to 'deserialize' or pythonify some or all of the incoming fields, for instance I might have a json object like
{
'id': 1,
'created_at': '2021-05-27T03:22:38Z',
'count': '3'
}
and I would like a way to "automatically" deserialize the data, similar to how djangorestframework serializers work where fields like "created_at" could be defined as datetime fields, and you could optionally cast 'count' as an integer, and run something like
...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/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有多个众所周知的模块来执行序列化(独立于任何框架):
Marshmallow: https://marshmallow .readthedocs.io/en/stable/
Typesystem(由 DRF 的创建者提供): https://github.com/encode/typesystem
您可以如果您的用例很简单,也可以基于 DRF 序列化器代码执行您自己的序列化器,或者只是执行验证/转换的字典字段的查找。
You have multiple well knowns module to perform serialization (independant of any framework):
Marshmallow: https://marshmallow.readthedocs.io/en/stable/
Typesystem (by the creator of DRF): https://github.com/encode/typesystem
You can also do your own serializer, based on DRF serializer code, if your use case is simple, or just perform a lookup of your dict fields that perform validation/transformation.