我們在接口測試的時候,如果因為一些原因,服務器沒有給我們響應,我們這邊就要在這等着,為了避免等待時間過長,我們可以在請求中加入一個超時時間,畢竟我們每天上班時間這么少,不能一直等下去~
timeout
requests 在經過以 timeout
參數設定的秒數時間之后停止等待響應。如果不使用,你的程序可能會永遠等待響應
用法:直接在請求框中加入timeout=XX值
小試牛刀
安靜請求谷歌搜索服務,因為需要FQ,這里會請求失敗,我們通過for循環多次請求並用rty來捕捉錯誤異常
# coding:utf-8 import requests import time url = 'https://www.google.com/?hl=zh_CN' t1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print('開始時間:'+t1) for i in range(1,3): try: r = requests.get(url,timeout=5) t2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("請求成功,請求時間是:{}".format(t2)) except Exception as e: t3 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("請求失敗,請求時間是:{}".format(t3)) print('失敗原因:%s'%e)
這里可以通過查看請求的時間差看出,5秒過后就報出異常
如果不加timeout限制的,看看請求時間為多長
# coding:utf-8 import requests import time url = 'https://www.google.com/?hl=zh_CN' t1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print('開始時間:'+t1) for i in range(1,3): try: r = requests.get(url) t2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("請求成功,請求時間是:{}".format(t2)) except Exception as e: t3 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("請求失敗,請求時間是:{}".format(t3)) print('失敗原因:%s'%e)
我們可以從下圖中看到,如果不加請求超時的話,時間就有點長了。