📜  Requests-处理超时

📅  最后修改于: 2020-10-21 08:33:55             🧑  作者: Mango


 

超时可以轻松添加到您请求的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(, '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的响应。