日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

python接口自动化(十七) requests获取响应时间(elapsed)与超时(timeout)

發布時間:2023/12/13 综合教程 33 生活家
生活随笔 收集整理的這篇文章主要介紹了 python接口自动化(十七) requests获取响应时间(elapsed)与超时(timeout) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言

requests發請求時,接口的響應時間,也是我們需要關注的一個點,如果響應時間太長,也是不合理的。

如果服務端沒及時響應,也不能一直等著,可以設置一個timeout超時的時間。

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.

 從發送請求到響應到達之間經過的時間量(以時間增量表示)。此屬性專門度量從發送請求的第一個字節到完成對頭的解析所用的時間。因此,它不受使用響應內容或stream關鍵字參數值的影響。 

2.用help()查看elapsed里面的方法

import requests
r=requests.get("https://www.baidu.com")
print(help(r.elapsed))

 elapsed里面幾個方法介紹

total_seconds 總時長,單位秒
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. 最大時間
min = datetime.timedelta(days=-999999999) 最小時間
resolution = datetime.timedelta(microseconds=1) 最小時間單位

獲取響應時間

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)

響應結果

2.網上很多資料寫的是用microseconds獲取響應時間,當請求小于1s時,發現不出什么問題,如果時間超過1s,問題就來了。

(很顯然,大于1s的時候,只截取了后面的小數部分)

3.所以獲取響應時間的正確姿勢應該是:r.elapsed.total_seconds(),單位是s

timeout超時

1.如果一個請求響應時間比較長,不能一直等著,可以設置一個超時時間,讓它拋出異常。

2.如下請求,設置超時為1s,那么就會拋出這個異常: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)

越努力,越幸運!!!
good good study,day day up!!!

總結

以上是生活随笔為你收集整理的python接口自动化(十七) requests获取响应时间(elapsed)与超时(timeout)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。