python接口自动化(十七) requests获取响应时间(elapsed)与超时(timeout)
前言
requests發(fā)請(qǐng)求時(shí),接口的響應(yīng)時(shí)間,也是我們需要關(guān)注的一個(gè)點(diǎn),如果響應(yīng)時(shí)間太長(zhǎng),也是不合理的。
如果服務(wù)端沒(méi)及時(shí)響應(yīng),也不能一直等著,可以設(shè)置一個(gè)timeout超時(shí)的時(shí)間。
elapsed官方文檔
1.elapsed方法的官方文檔地址:http://cn.python-requests.org/zh_CN/latest/api.html
elapsed = None The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the stream keyword argument.
從發(fā)送請(qǐng)求到響應(yīng)到達(dá)之間經(jīng)過(guò)的時(shí)間量(以時(shí)間增量表示)。此屬性專門度量從發(fā)送請(qǐng)求的第一個(gè)字節(jié)到完成對(duì)頭的解析所用的時(shí)間。因此,它不受使用響應(yīng)內(nèi)容或stream關(guān)鍵字參數(shù)值的影響。
2.用help()查看elapsed里面的方法
import requests
r=requests.get("https://www.baidu.com")
print(help(r.elapsed))
elapsed里面幾個(gè)方法介紹
total_seconds 總時(shí)長(zhǎng),單位秒
microseconds: Number of microseconds (>= 0 and less than 1 second) 獲取微妙部分,大于0小于1秒
seconds:Number of seconds (>= 0 and less than 1 day) 秒,大于0小于1天
max = datetime.timedelta(days=999999999, seconds=86399, microseconds=9. 最大時(shí)間
min = datetime.timedelta(days=-999999999) 最小時(shí)間
resolution = datetime.timedelta(microseconds=1) 最小時(shí)間單位
獲取響應(yīng)時(shí)間
1.獲取elapsed不同的返回值
import requests
r=requests.get("https://www.baidu.com")
print(r.elapsed)
print(r.elapsed.total_seconds())
print(r.elapsed.microseconds)
print(r.elapsed.seconds)
print(r.elapsed.days)
print(r.elapsed.max)
print(r.elapsed.min)
print(r.elapsed.resolution)
響應(yīng)結(jié)果
2.網(wǎng)上很多資料寫的是用microseconds獲取響應(yīng)時(shí)間,當(dāng)請(qǐng)求小于1s時(shí),發(fā)現(xiàn)不出什么問(wèn)題,如果時(shí)間超過(guò)1s,問(wèn)題就來(lái)了。
(很顯然,大于1s的時(shí)候,只截取了后面的小數(shù)部分)
3.所以獲取響應(yīng)時(shí)間的正確姿勢(shì)應(yīng)該是:r.elapsed.total_seconds(),單位是s
timeout超時(shí)
1.如果一個(gè)請(qǐng)求響應(yīng)時(shí)間比較長(zhǎng),不能一直等著,可以設(shè)置一個(gè)超時(shí)時(shí)間,讓它拋出異常。
2.如下請(qǐng)求,設(shè)置超時(shí)為1s,那么就會(huì)拋出這個(gè)異常:requests.exceptions.ConnectionError: HTTPSConnectionPool
import requests
a=requests.get("http://cn.python-requests.org/zh_CN/latest/",timeout=1)
print(a.elapsed)
print(a.elapsed.total_seconds())
print(a.elapsed.microseconds)
越努力,越幸運(yùn)!!!
good good study,day day up!!!
總結(jié)
以上是生活随笔為你收集整理的python接口自动化(十七) requests获取响应时间(elapsed)与超时(timeout)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java rest风格传参_Spring
- 下一篇: java语言编写进制转换_Java 3种