python一个类有几个实例对象_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协议安装到此适配器后,我使用pickle将对象持久化为redis,如下所示:

session = pickle.dumps(r)

redis.hset('sessions',id,session)

我尝试取消对会话对象的取消时出现问题:

s=redis.hget('sessions', id)

pickle.loads(s)

Traceback (most recent call last):

File "", line 1, in

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添加到我的会话之前,序列化运行良好.

所以我想这是定制类酸洗/去除斑点的问题.

更新:

在我将__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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值