How can I serialize a MongoDB ObjectId with Marshmallow?

前端 未结 4 1484
你的背包
你的背包 2021-02-14 07:48

I\'m building and API on top of Flask using marshmallow and mongoengine. When I make a call and an ID is supposed to be serialized I receive the following error:



        
4条回答
  •  忘掉有多难
    2021-02-14 08:04

    You can extend the fields.Field class to create your own field. Here's how marshmallow-mongoengine (mentioned in another answer) implements this:

    import bson
    from marshmallow import ValidationError, fields, missing
    
    class ObjectId(fields.Field):
        def _deserialize(self, value, attr, data):
            try:
                return bson.ObjectId(value)
            except Exception:
                raise ValidationError("invalid ObjectId `%s`" % value)
    
        def _serialize(self, value, attr, obj):
            if value is None:
                return missing
            return str(value)
    

    and then:

    class MySchema(Schema):
        id = ObjectId()
    

    (I found this useful when not using MongoEngine, just using pymongo)

提交回复
热议问题