如何序列化umongo文档

How to serialize umongo documents

假设我有以下示例:

from datetime import datetime
import dill
from pymongo import MongoClient
from umongo import Instance, Document, fields, validate

db = MongoClient().test
instance = Instance(db)

@instance.register
class User(Document):
    email = fields.EmailField(required=True, unique=True)
    birthday = fields.DateTimeField(validate=validate.Range(min=datetime(1900, 1, 1)))
    friends = fields.ListField(fields.ReferenceField("User"))

    class Meta:
        collection = db.user

User.ensure_indexes()

goku = User(email='goku@sayen.com', birthday=datetime(1984, 11, 20))
goku.commit()

found_goku = User.find_one({"email": 'goku@sayen.com'})
with open("dumped.dil", "wb") as out_file:
    dill.dump(found_goku, out_file)

这会导致 dill.dump 出现以下错误:

_pickle.PicklingError: Can't pickle <Implementation class 'tests.test_serialize_umongo.User'>: it's not found as tests.test_serialize_umongo.User

我知道我不能简单地 pickle 用户,因为我不能 pickle 数据库实例。我想使用 umongo 的 dump 和覆盖 __getstate__ 将用户腌制到字典,但我不知道如何解决这个 it's not found as 错误。

如果我没理解错的话,我相信你要找的是以下内容。本质上,我们使用文档自己的 dump() 方法将序列化文档作为要 pickle 的用户传递。这里唯一的区别是最后一行:dill.dump(found_goku.dump(), out_file):

from datetime import datetime
import dill
from pymongo import MongoClient
from umongo import Instance, Document, fields, validate

db = MongoClient().test
instance = Instance(db)

@instance.register
class User(Document):
    email = fields.EmailField(required=True, unique=True)
    birthday = fields.DateTimeField(validate=validate.Range(min=datetime(1900, 1, 1)))
    friends = fields.ListField(fields.ReferenceField("User"))

    class Meta:
        collection = db.user

User.ensure_indexes()

goku = User(email='goku@sayen.com', birthday=datetime(1984, 11, 20))
goku.commit()

found_goku = User.find_one({"email": 'goku@sayen.com'})
with open("dumped.dil", "wb") as out_file:
    dill.dump(found_goku.dump(), out_file)