python - Marshmallow serialization - a way to catch exceptions on a per field basis?
问题描述
Is there a way to catch exceptions (that occur when accessing a property) on a per-field basis with marshmallow [1] ?
I want to use marshmallow to serialize documents of a mongo db (mongoengine) database. With nested schemas, referenced objects are serialized as well.
However, in case of a reference that does not exist, mongoengine throws an error. I would like to catch that error in the process of serialization ( e.g and set field null)
[1] library for converting complex datatypes, such as objects, to and from native Python datatypes https://marshmallow.readthedocs.io/en/3.0/api_reference.html
解决方案
I ended up subclassing the Nested
field and overriding the get_value
method.
from marshmallow import Schema, fields
from mongoengine.errors import DoesNotExist
class SafeNested(fields.Nested):
def get_value(self, *args, **kwargs):
try:
return super().get_value(*args, **kwargs)
except DoesNotExist:
return {}
推荐阅读
- amazon-s3 - 我可以使用 aws-glue 将数据加载到 aerospike 中吗?
- facebook - 依赖于测试用户创建限制的测试 Facebook 应用程序的 E2E 测试
- android - 在 UploadTask onSuccessListener 中返回数据
- amazon-web-services - 导出 Lambda ARN
- elasticsearch - 如何为“未来 7 天”进行 ElasticSearch 日期直方图聚合
- python - 即使在 for 循环中不触及它,列表也会发生变化
- python - 使用 numpy.savetxt() 将数据写入 csv 时缺少第一个条目
- c++11 - c++11 使用正则表达式进行输入验证
- ruby-on-rails - 将参数拆分为数组元素
- lua - 如何在 Google Colaboratory 上修复 Torch 中的“/bin/bash: th: command not found”错误