1. 程式人生 > >gevent和requests同時使用報requests.exceptions.ReadTimeout:HTTPSConnectionPool(host='www.baidu.com', port=4

gevent和requests同時使用報requests.exceptions.ReadTimeout:HTTPSConnectionPool(host='www.baidu.com', port=4

最近專案需要用協程來處理網站併發訪問,使用了Gevent這個庫,訪問網站用requests,然而訪問https的url時報錯:

>>> from gevent import monkey; monkey.patch_socket()
>>> import gevent
>>> url='https://www.baidu.com'
>>> requests.get(url)
requests.exceptions.ReadTimeout:HTTPSConnectionPool(host='www.baidu.com', port=443
): Read timed out. (read timeout=None)

一開始還以為是網路連線的問題,然而使用wget並沒有問題。設定requests的timeout引數同樣沒有作用。改用urllib2庫,報的是下面這個異常:

urllib2.URLError: <urlopen error [Errno 2] _ssl.c:504: The operation did not complete (read)>

得到了解決方法:

>>> from gevent import monkey; monkey.patch_ssl()
>>> 
requests.get(url) <Response [200]>

這次的問題是因為對Gevent庫不熟悉,同時只想著貼上程式碼完成功能。結果GG了。