urllib3.HTTPSConnectionPool错误

时间:2015-04-28 01:03:18

标签: python-2.7 urllib3

我正在尝试多次请求RestAPI资源。为了节省时间,我尝试使用urllib3.HTTPSConnectionPool而不是urllib2。但是,它一直在向我抛出以下错误:

Traceback (most recent call last):
  File "LCRestapi.py", line 135, in <module>
    listedLoansFast(version, key, showAll='false')
  File "LCRestapi.py", line 55, in listedLoansFast
    pool.urlopen('GET',url+resource,headers={'Authorization':key})
  File "/Library/Python/2.7/site-packages/urllib3/connectionpool.py", line 515, in urlopen
    raise HostChangedError(self, url, retries)
urllib3.exceptions.HostChangedError: HTTPSConnectionPool(host='https://api.lendingclub.com/api/investor/v1/loans/listing?showAll=false', port=None): Tried to open a foreign host with url: https://api.lendingclub.com/api/investor/v1/loans/listing?showAll=false

我正在使用python-2.7.6

这是我的代码:

manager = urllib3.PoolManager(1)
url = 'https://api.lendingclub.com/api/investor/v1/loans/listing?showAll=false'
pool = urllib3.HTTPSConnectionPool(url+resource, maxsize=1, headers={'Authorization':key})
r = pool.request('GET',url+resource)
print r.data

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

问题在于您创建的是PoolManager但从未使用过它。相反,您还要创建HTTPSConnectionPool(绑定到特定主机)并使用它而不是PoolManagerPoolManager会代表您自动管理HTTPSConnectionPool个对象,因此您无需担心。

这应该有效:

# Your example called this `manager`
http = urllib3.PoolManager()

url = 'https://api.lendingclub.com/api/investor/v1/loans/listing?showAll=false'
headers = {'Authorization': key}

# Your example did url+resource, but let's assume the url variable
# contains the combined absolute url.
r = http.request('GET', url, headers=headers)
print r.data

如果您愿意,可以指定PoolManager的大小,但除非您尝试通过将资源限制为线程池来尝试做一些不寻常的事情,否则您不需要这样做。