問題描述:
有幾台服務器上都部署了一個雙進程的項目,有一天忽然幾台服務器都卡死了
起初我還懷疑是自己多進程中開多線程引發的內存占用問題,查看代碼並壓力測試后發現和內存沒多大關系
我拿出幾台服務器的日志對比分析,發現幾台機器的每一個進程的日志出現異常時間幾乎都是一個時間,並且都是在接口請求之后卡住了
很明顯最大可能是服務端出了問題,詢問后台人員確實在那個時間后台服務器出現過異常
那么問題來了,為什么呢???百度之后發現了這篇文章講解了其中的原因: 》》參考鏈接《《
網絡請求不可避免會遇上請求超時的情況,在 requests 中,如果不設置你的程序可能會永遠失去響應。
超時又可分為連接超時和讀取超時,簡單的說,連接超時就是發起請求連接到連接建立之間的最大時長,讀取超時就是連接成功開始到服務器返回響應之間等待的最大時長。
1.連接超時
連接超時指的是在你的客戶端實現到遠端機器端口的連接時(對應的是connect()),Request 等待的秒數。
默認值大概為:21秒
import time import requests url = 'http://www.google.com.hk' print(time.strftime('%Y-%m-%d %H:%M:%S')) try: html = requests.get(url, timeout=5).text print('success') except requests.exceptions.RequestException as e: print(e) print(time.strftime('%Y-%m-%d %H:%M:%S'))
因為 google 被牆了,所以無法連接,錯誤信息顯示 connect timeout(連接超時)
2018-12-14 14:38:20 HTTPConnectionPool(host='www.google.com.hk', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x00000000047F80F0>, 'Connection to www.google.com.hk timed out. (connect timeout=5)')) 2018-12-14 14:38:25
2.讀取超時
讀取超時指的就是客戶端等待服務器發送請求的時間。(特定地,它指的是客戶端要等待服務器發送字節之間的時間。在 99.9% 的情況下這指的是服務器發送第一個字節之前的時間)。
默認值:讀取超時是沒有默認值的,如果不設置,程序將一直處於等待狀態。我們的爬蟲經常卡死又沒有任何的報錯信息,原因就在這里了。
查看requests源碼可以發現:

timeout可以傳一個浮點數,也可以傳一個元組
如果你設置了一個單一的值作為 timeout,這一 timeout 值將會用作 connect(連接超時) 和 read (讀取超時)二者的 timeout,如下所示:
r = requests.get('https://github.com', timeout=5)
如果要分別制定,就傳入一個元組,(連接超時,讀取超時)如:
requests.post(url, headers=headers,data=info_json, timeout=(5,20))
黑板課爬蟲闖關的第四關正好網站人為設置了一個15秒的響應等待時間,拿來做說明最好不過了。
import time import requests url_login = 'http://www.heibanke.com/accounts/login/?next=/lesson/crawler_ex03/' session = requests.Session() session.get(url_login) token = session.cookies['csrftoken'] session.post(url_login, data={'csrfmiddlewaretoken': token, 'username': 'xx', 'password': 'xx'}) print(time.strftime('%Y-%m-%d %H:%M:%S')) url_pw = 'http://www.heibanke.com/lesson/crawler_ex03/pw_list/' try: html = session.get(url_pw, timeout=(5, 10)).text print('success') except requests.exceptions.RequestException as e: print(e) print(time.strftime('%Y-%m-%d %H:%M:%S'))
錯誤信息中顯示的是 read timeout(讀取超時)。
2018-12-14 15:20:47 HTTPConnectionPool(host='www.heibanke.com', port=80): Read timed out. (read timeout=10) 2018-12-14 15:20:57
3.超時重試
一般超時我們不會立即返回,而會設置一個三次重連的機制。
def gethtml(url): i = 0 while i < 3: try: html = requests.get(url, timeout=5).text return html except requests.exceptions.RequestException: i += 1
其實 requests 已經幫我們封裝好了。(但是代碼好像變多了...)
import time import requests from requests.adapters import HTTPAdapter s = requests.Session() s.mount('http://', HTTPAdapter(max_retries=3)) s.mount('https://', HTTPAdapter(max_retries=3)) print(time.strftime('%Y-%m-%d %H:%M:%S')) try: r = s.get('http://www.google.com.hk', timeout=5) return r.text except requests.exceptions.RequestException as e: print(e) print(time.strftime('%Y-%m-%d %H:%M:%S'))
ax_retries 為最大重試次數,重試3次,加上最初的一次請求,一共是4次,所以上述代碼運行耗時是20秒而不是15秒
2018-12-14 15:34:03 HTTPConnectionPool(host='www.google.com.hk', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x0000000013269630>, 'Connection to www.google.com.hk timed out. (connect timeout=5)')) 2018-12-14 15:34:23
