Requests - 处理超时
您可以轻松将超时添加到您请求的 URL。碰巧的是,您正在使用第三方 URL 并等待响应。为 URL 提供超时始终是一种很好的做法,因为我们可能希望 URL 在一定时间范围内响应或错误。不这样做可能会导致无限期地等待该请求。
我们可以使用超时参数为 URL 提供超时,并以秒为单位传递值,如下例所示 −
示例
import requests
getdata =
requests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001)
print(getdata.text)
输出
raise ConnectTimeout(e, request=request) requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='jsonplaceholder.typicode.com', port=443): Max retries exceeded with url: /users (Caused by Connect TimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x000000B02AD E76A0>, 'Connection to jsonplaceholder.typicode.com timed out. (connect timeout = 0.001)'))
给出的超时如下 −
getdata =
requests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001)
执行抛出连接超时错误,如输出所示。给出的超时为 0.001,请求无法返回响应并抛出错误。现在,我们将增加超时并检查。
示例
import requests
getdata =
requests.get('https://jsonplaceholder.typicode.com/users',timeout=1.000)
print(getdata.text)
输出
E:\prequests>python makeRequest.py
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
]
超时 1 秒后,我们可以获得所请求 URL 的响应。

