2

我正在尝试多次请求 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

谢谢您的帮助!

4

1 回答 1

3

问题是您正在创建一个PoolManager但从未使用它。相反,您还创建了一个HTTPSConnectionPool(绑定到特定主机)并使用它而不是PoolManager. PoolManager它将自动代表您管理对象,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,但除非您尝试做一些不寻常的事情,将资源限制在线程池中,否则您不需要这样做。

于 2015-04-28T02:22:48.683 回答