如何序列化umongo文档

时间:2019-02-07 09:40:21

标签: python serialization pickle umongo

假设我有以下示例:

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

我了解到我不能简单地对用户进行腌制,因为我不能对数据库实例进行腌制。我想使用umongo的dump并覆盖__getstate__来使用户腌制到Dict,但是我不知道如何解决此it's not found as错误。

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,那么我相信您正在寻找以下内容。本质上,我们使用文档自己的dump()方法来传递序列化的文档作为要腌制的用户。唯一的不同是最后一行: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)