2015-10-17 15 views
1

我有一個put和get函數,它插入到MongoDB的:如何在MongoDB中存儲鎖定對象?

def put(self,key,value): 
    key = self.path+"&&"+key 
    value1 = Binary(pickle.dumps(value)) 
    entry = {"keyname":key,"info":value1}  
    self.filenode.update({"keyname":key}, { "$set" : entry }, upsert=True) 

def get(self,key): 
    key1 = key 
    key = self.path+"&&"+key 
    res = self.filenode.find_one({"keyname":key})   
    if "info" in res: 
     x = res["info"] 
     res1 = pickle.loads(x) 
     return res1 
    else: 
     return None 

這工作如果放值是簡單的類型,如字符串,快譯通等,但如果值是一個對象時,它是不能夠鹹菜在put函數中。我得到的錯誤是:

raise TypeError, "can't pickle %s objects" % base.__name__ 

類型錯誤:無法鹹菜鎖定對象

回答

1

有Python的文檔的讀取上的序列化 - pickle — Python object serialization。如果你控制對象的定義,你可以提供一個__getstate__()方法,它可以刪除不可序列化的屬性,如鎖。

我用它來設置一個鎖到None,然後使用__setstate__()作爲反序列化掛鉤重新初始化鎖。

3

你可以使用更好的序列化程序,如dill,它可以醃製Lock和python中的大多數對象。

>>> import threading 
>>> l = threading.Lock() 
>>> 
>>> import dill 
>>> dill.dumps(l) 
'\x80\x02cdill.dill\n_create_lock\nq\x00\x89\x85q\x01Rq\x02.' 

然後,您可以將大多數對象保存到數據庫,首先轉換爲pickled字符串。