Skip to content
Myr

Merge pull request #2176 from kevinburke/connect

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Add support for connect timeouts

authored by Kenneth Reitz · committed by Kenneth Reitz · parents c879873, 7f236fc · Browse files · 6 files+130 added−13 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+130 added−13 removed

  • other:+130 added−13 removed

6 files+130 added−13 removed

modified:docs/user/advanced.rst+38 added
705 unmodified lines
706Two excellent examples are `grequests`_ and `requests-futures`_.707708.. _`grequests`: https://github.com/kennethreitz/grequests709.. _`requests-futures`: https://github.com/ross/requests-futures710711Timeouts712--------713714Most requests to external servers should have a timeout attached, in case the715server is not responding in a timely manner. Without a timeout, your code may716hang for minutes or more.717718The **connect** timeout is the number of seconds Requests will wait for your719client to establish a connection to a remote machine (corresponding to the720`connect()`_) call on the socket. It's a good practice to set connect timeouts721to slightly larger than a multiple of 3, which is the default `TCP packet722retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.723724Once your client has connected to the server and sent the HTTP request, the725**read** timeout is the number of seconds the client will wait for the server726to send a response. (Specifically, it's the number of seconds that the client727will wait *between* bytes sent from the server. In 99.9% of cases, this is the728time before the server sends the first byte).729730If you specify a single value for the timeout, like this::731732 r = requests.get('https://github.com', timeout=5)733734The timeout value will be applied to both the ``connect`` and the ``read``735timeouts. Specify a tuple if you would like to set the values separately::736737 r = requests.get('https://github.com', timeout=(3.05, 27))738739If the remote server is very slow, you can tell Requests to wait forever for740a response, by passing None as a timeout value and then retrieving a cup of741coffee.742743.. code-block:: python744745 r = requests.get('https://github.com', timeout=None)746747.. _`connect()`: http://linux.die.net/man/2/connect
modified:docs/api.rst+1 added-1 removed
3 unmodified lines
4===================56.. module:: requests78This part of the documentation covers all the interfaces of Requests. For8This part of the documentation covers all the interfaces of Requests. For9parts where Requests depends on external libraries, we document the most10important right here and provide links to the canonical documentation.1112
263 unmodified lines
modified:requests/adapters.py+25 added-8 removed
13 unmodified lines
14from .packages.urllib3 import Retry15from .packages.urllib3.poolmanager import PoolManager, proxy_from_url16from .packages.urllib3.response import HTTPResponse17from .packages.urllib3.util import Timeout as TimeoutSauce18from .compat import urlparse, basestring, urldefrag, unquote18from .compat import urlparse, basestring, urldefrag19from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,20 prepend_scheme_if_needed, get_auth_from_url)21from .structures import CaseInsensitiveDict22from .packages.urllib3.exceptions import MaxRetryError23from .packages.urllib3.exceptions import TimeoutError24from .packages.urllib3.exceptions import SSLError as _SSLError22from .packages.urllib3.exceptions import ConnectTimeoutError23from .packages.urllib3.exceptions import HTTPError as _HTTPError24from .packages.urllib3.exceptions import MaxRetryError25from .packages.urllib3.exceptions import ProxyError as _ProxyError26from .packages.urllib3.exceptions import ReadTimeoutError27from .packages.urllib3.exceptions import SSLError as _SSLError28from .cookies import extract_cookies_to_jar28from .exceptions import ConnectionError, Timeout, SSLError, ProxyError29from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,30 ProxyError)31from .auth import _basic_auth_str3233DEFAULT_POOLBLOCK = False34DEFAULT_POOLSIZE = 10
281 unmodified lines
316317 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.318 :param stream: (optional) Whether to stream the request content.319 :param timeout: (optional) The timeout on the request.320 :type timeout: float or tuple (connect timeout, read timeout), eg (3.1, 20)321 :param verify: (optional) Whether to verify SSL certificates.322 :param cert: (optional) Any user-provided SSL certificate to be trusted.323 :param proxies: (optional) The proxies dictionary to apply to the request.324 """
5 unmodified lines
330 self.add_headers(request)331332 chunked = not (request.body is None or 'Content-Length' in request.headers)333334 if isinstance(timeout, tuple):335 try:336 connect, read = timeout337 timeout = TimeoutSauce(connect=connect, read=read)338 except ValueError as e:339 # this may raise a string formatting error.340 err = ("Invalid timeout {0}. Pass a (connect, read) "341 "timeout tuple, or a single float to set "342 "both timeouts to the same value".format(timeout))343 raise ValueError(err)344 else:331 timeout = TimeoutSauce(connect=timeout, read=timeout)345 timeout = TimeoutSauce(connect=timeout, read=timeout)346347 try:348 if not chunked:349 resp = conn.urlopen(
53 unmodified lines
403 except socket.error as sockerr:404 raise ConnectionError(sockerr, request=request)405406 except MaxRetryError as e:407 if isinstance(e.reason, ConnectTimeoutError):408 raise ConnectTimeout(e, request=request)409410 raise ConnectionError(e, request=request)411412 except _ProxyError as e:413 raise ProxyError(e)414415 except (_SSLError, _HTTPError) as e:416 if isinstance(e, _SSLError):417 raise SSLError(e, request=request)401 elif isinstance(e, TimeoutError):402 raise Timeout(e, request=request)418 elif isinstance(e, ReadTimeoutError):419 raise ReadTimeout(e, request=request)420 else:421 raise422423 return self.build_response(request, resp)
modified:requests/exceptions.py+16 added-1 removed
42 unmodified lines
43 """An SSL error occurred."""444546class Timeout(RequestException):47 """The request timed out."""47 """The request timed out.4849 Catching this error will catch both :exc:`ConnectTimeout` and50 :exc:`ReadTimeout` errors.51 """525354class ConnectTimeout(ConnectionError, Timeout):55 """The request timed out while trying to connect to the server.5657 Requests that produce this error are safe to retry58 """596061class ReadTimeout(Timeout):62 """The server did not send any data in the allotted amount of time."""636465class URLRequired(RequestException):66 """A valid URL is required to make a request."""6768
22 unmodified lines
modified:requests/structures.py+1 added-1 removed
21 unmodified lines
22 All keys are expected to be strings. The structure remembers the23 case of the last key to be set, and ``iter(instance)``,24 ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``25 will contain case-sensitive keys. However, querying and contains26 testing is case insensitive:26 testing is case insensitive::2728 cid = CaseInsensitiveDict()29 cid['Accept'] = 'application/json'30 cid['aCCEPT'] == 'application/json' # True
74 unmodified lines
modified:test_requests.py+49 added-2 removed
16 unmodified lines
17from requests.auth import HTTPDigestAuth, _basic_auth_str18from requests.compat import (19 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)20from requests.cookies import cookiejar_from_dict, morsel_to_cookie21from requests.exceptions import InvalidURL, MissingSchema, ConnectionError21from requests.exceptions import (InvalidURL, MissingSchema, ConnectTimeout,22 ReadTimeout, ConnectionError, Timeout)23from requests.models import PreparedRequest24from requests.structures import CaseInsensitiveDict25from requests.sessions import SessionRedirectMixin26from requests.models import urlencode
11 unmodified lines
38 def u(s):39 return s.decode('unicode-escape')404142# Requests to this URL should always fail with a connection timeout (nothing43# listening on that port)44TARPIT = "http://10.255.255.1"45HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')46# Issue #1483: Make sure the URL always has a trailing slash47HTTPBIN = HTTPBIN.rstrip('/') + '/'48
1262 unmodified lines
13111312class TestTimeout:1313 def test_stream_timeout(self):1314 try:1311 requests.get('https://httpbin.org/delay/10', timeout=5.0)1315 requests.get('https://httpbin.org/delay/10', timeout=2.0)1316 except requests.exceptions.Timeout as e:1317 assert 'Read timed out' in e.args[0].args[0]13181319 def test_invalid_timeout(self):1320 with pytest.raises(ValueError) as e:1321 requests.get(httpbin('get'), timeout=(3, 4, 5))1322 assert '(connect, read)' in str(e)13231324 with pytest.raises(ValueError) as e:1325 requests.get(httpbin('get'), timeout="foo")1326 assert 'must be an int or float' in str(e)13271328 def test_none_timeout(self):1329 """ Check that you can set None as a valid timeout value.13301331 To actually test this behavior, we'd want to check that setting the1332 timeout to None actually lets the request block past the system default1333 timeout. However, this would make the test suite unbearably slow.1334 Instead we verify that setting the timeout to None does not prevent the1335 request from succeeding.1336 """1337 r = requests.get(httpbin('get'), timeout=None)1338 assert r.status_code == 20013391340 def test_read_timeout(self):1341 try:1342 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1343 assert False, "The recv() request should time out."1344 except ReadTimeout:1345 pass13461347 def test_connect_timeout(self):1348 try:1349 requests.get(TARPIT, timeout=(0.1, None))1350 assert False, "The connect() request should time out."1351 except ConnectTimeout as e:1352 assert isinstance(e, ConnectionError)1353 assert isinstance(e, Timeout)13541355 def test_total_timeout_connect(self):1356 try:1357 requests.get(TARPIT, timeout=(0.1, 0.1))1358 assert False, "The connect() request should time out."1359 except ConnectTimeout:1360 pass136113621363SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))136413651366class RedirectSession(SessionRedirectMixin):
115 unmodified lines