欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > 解释python requests包的timeout

解释python requests包的timeout

2025/8/31 19:25:49 来源:https://blog.csdn.net/xiaolixi199311/article/details/142530947  浏览:    关键词:解释python requests包的timeout

解释python requests包的timeout

哈哈哈。。。。垃圾python又来了

1 问题

你能看懂下面两个timeout的含义就不用看下面的内容了。

requests.get('http://example.com', timeout=(2, 5))
requests.get('http://127.0.0.1:5000/api',timeout=1)
  • 官网解释!!!
    在这里插入图片描述

  • requests的入门文章

2 结论

  1. 一个参数:requests.get('http://127.0.0.1:5000/api',timeout=1)连接或者读超时的时间,也就是timeout=(1, 1)
  2. 两个参数:requests.get('http://example.com', timeout=(2, 5))连接超时的时间2s,读超时时间5s。

2.1 ConnectTimeout-连接https://hub.docker.com/超时的案例

>>> requests.get('https://hub.docker.com/',timeout=1)
Traceback (most recent call last):File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connection.py", line 198, in _new_connsock = connection.create_connection(^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/util/connection.py", line 85, in create_connectionraise errFile "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/util/connection.py", line 73, in create_connectionsock.connect(sa)
TimeoutError: timed outThe above exception was the direct cause of the following exception:Traceback (most recent call last):File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 793, in urlopenresponse = self._make_request(^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 491, in _make_requestraise new_eFile "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 467, in _make_requestself._validate_conn(conn)File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 1099, in _validate_connconn.connect()File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connection.py", line 616, in connectself.sock = sock = self._new_conn()^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connection.py", line 207, in _new_connraise ConnectTimeoutError(
urllib3.exceptions.ConnectTimeoutError: (<urllib3.connection.HTTPSConnection object at 0x1065f8bc0>, 'Connection to hub.docker.com timed out. (connect timeout=1)')The above exception was the direct cause of the following exception:Traceback (most recent call last):File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/adapters.py", line 486, in sendresp = conn.urlopen(^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 847, in urlopenretries = retries.increment(^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/util/retry.py", line 515, in incrementraise MaxRetryError(_pool, url, reason) from reason  # type: ignore[arg-type]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='hub.docker.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x1065f8bc0>, 'Connection to hub.docker.com timed out. (connect timeout=1)'))During handling of the above exception, another exception occurred:Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/api.py", line 73, in getreturn request("get", url, params=params, **kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/api.py", line 59, in requestreturn session.request(method=method, url=url, **kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/sessions.py", line 589, in requestresp = self.send(prep, **send_kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/sessions.py", line 703, in sendr = adapter.send(request, **kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/adapters.py", line 507, in sendraise ConnectTimeout(e, request=request)
requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='hub.docker.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x1065f8bc0>, 'Connection to hub.docker.com timed out. (connect timeout=1)'))
>>> 

2.2 ReadTimeout-读超时的案例

(base)  ~/ cat python ss.py 
cat: python: No such file or directory
from flask import Flask, request, jsonify
import time
app = Flask(__name__)@app.route('/api', methods=['POST','GET'])
def api():time.sleep(2)# 在这里处理数据,例如:result = {'message': 'Hello, World!'}return jsonify(result)if __name__ == '__main__':app.run(debug=True)(base)  ~/ cat ss.py
from flask import Flask, request, jsonify
import time
app = Flask(__name__)@app.route('/api', methods=['POST','GET'])
def api():time.sleep(2)# 在这里处理数据,例如:result = {'message': 'Hello, World!'}return jsonify(result)if __name__ == '__main__':app.run(debug=True)(base)  ~/ 
(base)  ~/ 
(base)  ~/ 
(base)  ~/ python ss.py* Serving Flask app 'ss'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on http://127.0.0.1:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 118-547-680
127.0.0.1 - - [25/Sep/2024 19:03:55] "GET /api HTTP/1.1" 200 -
127.0.0.1 - - [25/Sep/2024 19:04:05] "GET /api HTTP/1.1" 200 -
>>> requests.get('http://127.0.0.1:5000/api',timeout=1)
Traceback (most recent call last):File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 537, in _make_requestresponse = conn.getresponse()^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connection.py", line 466, in getresponsehttplib_response = super().getresponse()^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/http/client.py", line 1428, in getresponseresponse.begin()File "/Users/admin/miniforge3/lib/python3.12/http/client.py", line 331, in beginversion, status, reason = self._read_status()^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/http/client.py", line 292, in _read_statusline = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/socket.py", line 707, in readintoreturn self._sock.recv_into(b)^^^^^^^^^^^^^^^^^^^^^^^
TimeoutError: timed outThe above exception was the direct cause of the following exception:Traceback (most recent call last):File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/adapters.py", line 486, in sendresp = conn.urlopen(^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 847, in urlopenretries = retries.increment(^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/util/retry.py", line 470, in incrementraise reraise(type(error), error, _stacktrace)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/util/util.py", line 39, in reraiseraise valueFile "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 793, in urlopenresponse = self._make_request(^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 539, in _make_requestself._raise_timeout(err=e, url=url, timeout_value=read_timeout)File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 370, in _raise_timeoutraise ReadTimeoutError(
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='127.0.0.1', port=5000): Read timed out. (read timeout=1)During handling of the above exception, another exception occurred:Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/api.py", line 73, in getreturn request("get", url, params=params, **kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/api.py", line 59, in requestreturn session.request(method=method, url=url, **kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/sessions.py", line 589, in requestresp = self.send(prep, **send_kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/sessions.py", line 703, in sendr = adapter.send(request, **kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/adapters.py", line 532, in sendraise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='127.0.0.1', port=5000): Read timed out. (read timeout=1)>>> 

2.3 读超时

>>> requests.get('http://127.0.0.1:5000/api',timeout=(1, 1))
Traceback (most recent call last):File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 537, in _make_requestresponse = conn.getresponse()^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connection.py", line 466, in getresponsehttplib_response = super().getresponse()^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/http/client.py", line 1428, in getresponseresponse.begin()File "/Users/admin/miniforge3/lib/python3.12/http/client.py", line 331, in beginversion, status, reason = self._read_status()^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/http/client.py", line 292, in _read_statusline = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/socket.py", line 707, in readintoreturn self._sock.recv_into(b)^^^^^^^^^^^^^^^^^^^^^^^
TimeoutError: timed outThe above exception was the direct cause of the following exception:Traceback (most recent call last):File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/adapters.py", line 486, in sendresp = conn.urlopen(^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 847, in urlopenretries = retries.increment(^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/util/retry.py", line 470, in incrementraise reraise(type(error), error, _stacktrace)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/util/util.py", line 39, in reraiseraise valueFile "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 793, in urlopenresponse = self._make_request(^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 539, in _make_requestself._raise_timeout(err=e, url=url, timeout_value=read_timeout)File "/Users/admin/miniforge3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 370, in _raise_timeoutraise ReadTimeoutError(
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='127.0.0.1', port=5000): Read timed out. (read timeout=1)During handling of the above exception, another exception occurred:Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/api.py", line 73, in getreturn request("get", url, params=params, **kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/api.py", line 59, in requestreturn session.request(method=method, url=url, **kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/sessions.py", line 589, in requestresp = self.send(prep, **send_kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/sessions.py", line 703, in sendr = adapter.send(request, **kwargs)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/Users/admin/miniforge3/lib/python3.12/site-packages/requests/adapters.py", line 532, in sendraise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='127.0.0.1', port=5000): Read timed out. (read timeout=1)
>>> 
>>> 
>>> 
>>> 

2.4 不超时

>>> 
>>> requests.get('http://127.0.0.1:5000/api',timeout=(1, 2.1))
<Response [200]>
>>> 
>>> requests.get('http://127.0.0.1:5000/api',timeout=2.1)
<Response [200]>
>>> 
>>> print(requests.get('http://127.0.0.1:5000/api',timeout=2.1).json())
{'message': 'Hello, World!'}
>>> 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词