Requests - 处理超时
Requests - 精通超时处理
Section titled “Requests - 精通超时处理”在进行网络请求时,尤其是对第三方服务,设置超时至关重要。没有超时设置,您的应用程序可能会无限期地等待永不来的响应。这会耗尽资源并降低用户体验。requests 库可以轻松配置超时。
您可以使用 timeout 参数指定超时时间(以秒为单位)。这可以是一个浮点数值表示总超时,或者是一个元组 (connect_timeout, read_timeout)。
- **连接超时:**等待与服务器建立连接的时间(以秒为单位)。
- **读取超时:**在连接建立后,等待服务器发送响应的时间(以秒为单位)。
示例:极短的超时
Section titled “示例:极短的超时”让我们设置一个不切实际的短连接超时,看看 requests 如何处理它。
import requests
try: response = requests.get('https://jsonplaceholder.typicode.com/users', timeout=0.001) print(response.text)except requests.exceptions.ConnectTimeout as e: print(f"Connection timed out: {e}")except requests.exceptions.ReadTimeout as e: print(f"Read timed out: {e}")except requests.exceptions.Timeout as e: print(f"A general timeout occurred: {e}")预期输出(会略有不同)
Section titled “预期输出(会略有不同)”Connection timed out: HTTPSConnectionPool(host='jsonplaceholder.typicode.com', port=443): Max retries exceeded with url: /users (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x...>, 'Connection to jsonplaceholder.typicode.com timed out. (connect timeout=0.001)'))上面的代码演示了如何捕获 ConnectTimeout 异常。0.001 秒的超时通常对于任何网络请求来说都太短,会导致这个错误。
示例:合理的超时
Section titled “示例:合理的超时”现在,我们使用一个更实际的超时值(例如,连接 5 秒,读取 10 秒)。
import requests
try: response = requests.get('https://jsonplaceholder.typicode.com/users', timeout=(5, 10)) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) print(response.json()[0]) # Print the first user object if successfulexcept requests.exceptions.Timeout as e: print(f"Timeout occurred: {e}")except requests.exceptions.RequestException as e: print(f"An error occurred: {e}")预期输出(为简洁起见已截断)
Section titled “预期输出(为简洁起见已截断)”{ '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' }}设置合理的超时后,请求很可能成功。我们还添加了 response.raise_for_status() 来健壮地处理 HTTP 错误。
**最佳实践:**对于外部请求,请始终使用超时。具体数值取决于您调用的服务预期的响应时间。不设置超时可能会导致您的请求无限期等待。
有关超时配置的更多详细信息,请参阅 Requests 官方文档关于超时的部分。