我在python中获取了一些对象值,我希望将它存储在mongodb中供以后使用,但没有运气
def callPylink(self):
from pylinkgrammar.linkgrammar import Parser
import sys
p = Parser()
linkage = p.parse_sent("When was Gandhi born")
try:
print "Linkage 0 ", linkage[0]
except:
print "error"
self.collection.insert(linkage[0].__dict__)
在插入行:
Linkage 0 <pylinkgrammar.linkgrammar.Linkage object at 0x92db84c>
Traceback (most recent call last):
File "objmongo.py", line 28, in <module>
data = obj.callPylink()
File "objmongo.py", line 23, in callPylink
self.collection.insert(linkage[0].__dict__)
File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 409, in insert
gen(), check_keys, self.uuid_subtype, client)
bson.errors.InvalidDocument: Cannot encode object: <S: When, was>
在mongo中存储python对象的其他方法是什么。
更新
pickled = pickle.dumps(linkage[0])
self.collection.insert(pickled)
给出错误:
File "objmongo.py", line 30, in <module>
data = obj.callPylink()
File "objmongo.py", line 25, in callPylink
self.collection.insert(pickled)
File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 409, in insert
gen(), check_keys, self.uuid_subtype, client)
File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 386, in gen
doc['_id'] = ObjectId()
TypeError: 'str' object does not support item assignment
答案 0 :(得分:2)
要在mongodb中存储字典,您的字典只能包含字符串键和mongodb可以序列化(编码)的那些类型的值。这不是这种情况。
您可以将复杂对象树序列化为字节字符串并使用pickle
模块将其反序列化,使用pickle.dumps(obj)
将对象序列化为字节字符串,并使用pickle.loads(bytestring)
反序列化对象< / p>
示例:给出以下类和实例
>>> class OurClass():
... def __init__(self, arg):
... self.arg = arg
...
>>> instance = OurClass(42)
我们导入pickle模块
>>> import pickle
>>> pickled = pickle.dumps(y)
>>> pickled
b'\x80\x03c__main__\nX\nq\x00)\x81q\x01}q\x02X\x03\x00\x00\x00argq\x03K*sb.'
pickled
是要存储到文档字段中的数据库的值,如:
my_doc = { 'linkage': pickled }
self.collection.insert(my_doc)
现在,您可以使用pickle.loads
>>> restored = pickle.loads(pickled)
>>> restored
<__main__.OurClass object at 0x7fc91cb35cf8>
>>> restored.arg
42