- 请求教程
- 请求 - 首页
- 请求 - 概述
- 请求 - 环境设置
- 请求 - HTTP 请求的工作原理?
- 请求 - 使用请求
- 处理 HTTP 请求的响应
- 请求 - HTTP 请求头
- 请求 - 处理 GET 请求
- 处理 POST、PUT、PATCH 和 DELETE 请求
- 请求 - 文件上传
- 请求 - 使用 Cookie
- 请求 - 处理错误
- 请求 - 处理超时
- 请求 - 处理重定向
- 请求 - 处理历史记录
- 请求 - 处理会话
- 请求 - SSL 认证
- 请求 - 身份验证
- 请求 - 事件挂钩
- 请求 - 代理
- 请求 - 使用请求进行网络抓取
- 请求 - 有用资源
- 请求 - 快速指南
- 请求 - 有用资源
- 请求 - 探讨
请求 - 处理超时
超时可以轻松添加到要请求的 URL。具体来说,您正在使用第三方 URL 并等待响应。最好对 URL 设置超时,因为我们可能希望 URL 在某个时间范围内用响应或错误进行响应。如果不这样做,可能会导致无限期地等待该请求。
我们可以使用 timeout 参数对 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 的响应。
广告