如何序列化 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错误。

如果我理解正确,我相信您正在寻找以下内容。实质上,我们使用文档自己的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)

相关内容

  • 没有找到相关文章

最新更新