是否有一种方法可以使用棉花糖[1]在每个字段中捕获异常(在访问属性时发生)?
我想使用棉花糖序列化mongo db(mongoengine)数据库的文档。 使用嵌套模式,引用的对象也将被序列化。
但是,如果引用不存在,mongoengine会引发错误。我想在序列化过程中捕获该错误(例如,将字段设置为null)
[1] 库,用于将复杂的数据类型(例如对象)与本机Python数据类型之间进行转换 https://marshmallow.readthedocs.io/en/3.0/api_reference.html
答案 0 :(得分:1)
我最终继承了Nested
字段的子类并覆盖了get_value
方法。
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 {}