相关疑难解决方法(0)

如何使用Marshmallow序列化MongoDB ObjectId?

我正在使用棉花糖和mongoengine在Flask上构建和API.当我打电话并且ID应该被序列化时,我收到以下错误:

TypeError: ObjectId('54c117322053049ba3ef31f3') is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

我看到了其他库的一些方法来覆盖ObjectId的处理方式.我还没有想到Marshmallow,有谁知道怎么做?

我的模型是:

class Process(db.Document):
    name = db.StringField(max_length=255, required=True, unique=True)
    created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
Run Code Online (Sandbox Code Playgroud)

我的序列化器:

class ProcessSerializer(Serializer):
    class Meta:
        fields = ("id", "created_at", "name")
Run Code Online (Sandbox Code Playgroud)

并且观点:

class ProcessView(Resource):
    def get(self, id):
        process = Process.objects.get_or_404(id)
        return ProcessSerializer(process).data
Run Code Online (Sandbox Code Playgroud)

python mongoengine flask marshmallow

7
推荐指数
1
解决办法
3902
查看次数

标签 统计

flask ×1

marshmallow ×1

mongoengine ×1

python ×1