我正在使用python請求庫並試圖保持會話。Python取消了一個對象,其中有一個類實例
由於我的主機上有多個IP,爲了使會話綁定到特定的IP,我創建了以下方法。
class SourceAddressAdapter(HTTPAdapter):
def __init__(self, source_address, **kwargs):
self.source_address = source_address
super(SourceAddressAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
source_address=self.source_address)
下面的代碼片用於調用這個類:
r = requests.Session()
r.mount('http://', SourceAddressAdapter((self.ip,0)))
r.mount('https://', SourceAddressAdapter((self.ip,0)))
安裝http和https協議到該適配器後,我用泡菜的對象持續到redis的如下:
session = pickle.dumps(r)
redis.hset('sessions',id,session)
當我嘗試取消會話對象時發生問題:
s=redis.hget('sessions', id)
pickle.loads(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/pickle.py", line 1382, in loads
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1217, in load_build
setstate(state)
File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 114, in __setstate__
block=self._pool_block)
File "network_driver.py", line 158, in init_poolmanager
source_address=self.source_address)
AttributeError: 'SourceAddressAdapter' object has no attribute 'source_address'
它抱怨SourceAddressAdapter沒有source_address屬性。在將此類SourceAddressAdapter添加到我的會話之前,序列化運行良好。
所以我想這是定製類酸洗/取出問題。
UPDATE:
它的工作原理我加入__getstate__
和__setstate__
方法後,進入SourceAddressAdapter
def __getstate__(self):
# it calls HTTPAdapter's __getstate__()
state = super(SourceAddressAdapter, self).__getstate__()
state['source_address'] = self.source_address
return state
def __setstate__(self,state):
self.source_address = state['source_address']
# Call HTTPAdapter's __setstate__ function to pack the attributes in parent class
super(SourceAddressAdapter, self).__setstate__(state)
SourceAddressAdapter位於何處? –
SourceAddressAdapter位於network_driver.py中,另一個文件main.py調用pickle – Yifei
主調用酸洗和拆卸? –