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
Provenance
- Commit
32e403a- Tree
0cd353a- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
Kenneth Reitz <me@kennethreitz.org>- Parent 1
c879873- Parent 2
7f236fc
6 files changed+130 added−13 removed
modified:docs/user/advanced.rst+38 added
705 unmodified lines706 Two excellent examples are `grequests`_ and `requests-futures`_.707 708 .. _`grequests`: https://github.com/kennethreitz/grequests709 .. _`requests-futures`: https://github.com/ross/requests-futures710+711+Timeouts712+--------713+714+Most requests to external servers should have a timeout attached, in case the715+server is not responding in a timely manner. Without a timeout, your code may716+hang for minutes or more.717+718+The **connect** timeout is the number of seconds Requests will wait for your719+client to establish a connection to a remote machine (corresponding to the720+`connect()`_) call on the socket. It's a good practice to set connect timeouts721+to slightly larger than a multiple of 3, which is the default `TCP packet722+retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.723+724+Once 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 server726+to send a response. (Specifically, it's the number of seconds that the client727+will wait *between* bytes sent from the server. In 99.9% of cases, this is the728+time before the server sends the first byte).729+730+If you specify a single value for the timeout, like this::731+732+ r = requests.get('https://github.com', timeout=5)733+734+The timeout value will be applied to both the ``connect`` and the ``read``735+timeouts. Specify a tuple if you would like to set the values separately::736+737+ r = requests.get('https://github.com', timeout=(3.05, 27))738+739+If the remote server is very slow, you can tell Requests to wait forever for740+a response, by passing None as a timeout value and then retrieving a cup of741+coffee.742+743+.. code-block:: python744+745+ r = requests.get('https://github.com', timeout=None)746+747+.. _`connect()`: http://linux.die.net/man/2/connectmodified:docs/api.rst+1 added-1 removed
3 unmodified lines4 ===================5 6 .. module:: requests7 8-This part of the documentation covers all the interfaces of Requests. For8+This part of the documentation covers all the interfaces of Requests. For9 parts where Requests depends on external libraries, we document the most10 important right here and provide links to the canonical documentation.11 12 263 unmodified linesmodified:requests/adapters.py+25 added-8 removed
13 unmodified lines14 from .packages.urllib3 import Retry15 from .packages.urllib3.poolmanager import PoolManager, proxy_from_url16 from .packages.urllib3.response import HTTPResponse17 from .packages.urllib3.util import Timeout as TimeoutSauce18-from .compat import urlparse, basestring, urldefrag, unquote18+from .compat import urlparse, basestring, urldefrag19 from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,20 prepend_scheme_if_needed, get_auth_from_url)21 from .structures import CaseInsensitiveDict22-from .packages.urllib3.exceptions import MaxRetryError23-from .packages.urllib3.exceptions import TimeoutError24-from .packages.urllib3.exceptions import SSLError as _SSLError22+from .packages.urllib3.exceptions import ConnectTimeoutError23 from .packages.urllib3.exceptions import HTTPError as _HTTPError24+from .packages.urllib3.exceptions import MaxRetryError25 from .packages.urllib3.exceptions import ProxyError as _ProxyError26+from .packages.urllib3.exceptions import ReadTimeoutError27+from .packages.urllib3.exceptions import SSLError as _SSLError28 from .cookies import extract_cookies_to_jar28-from .exceptions import ConnectionError, Timeout, SSLError, ProxyError29+from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,30+ ProxyError)31 from .auth import _basic_auth_str32 33 DEFAULT_POOLBLOCK = False34 DEFAULT_POOLSIZE = 10281 unmodified lines316 317 :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 lines330 self.add_headers(request)331 332 chunked = not (request.body is None or 'Content-Length' in request.headers)333 334+ 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)346 347 try:348 if not chunked:349 resp = conn.urlopen(53 unmodified lines403 except socket.error as sockerr:404 raise ConnectionError(sockerr, request=request)405 406 except MaxRetryError as e:407+ if isinstance(e.reason, ConnectTimeoutError):408+ raise ConnectTimeout(e, request=request)409+410 raise ConnectionError(e, request=request)411 412 except _ProxyError as e:413 raise ProxyError(e)414 415 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 raise422 423 return self.build_response(request, resp)modified:requests/exceptions.py+16 added-1 removed
42 unmodified lines43 """An SSL error occurred."""44 45 46 class Timeout(RequestException):47- """The request timed out."""47+ """The request timed out.48 49+ Catching this error will catch both :exc:`ConnectTimeout` and50+ :exc:`ReadTimeout` errors.51+ """52 53+54+class ConnectTimeout(ConnectionError, Timeout):55+ """The request timed out while trying to connect to the server.56+57+ Requests that produce this error are safe to retry58+ """59+60+61+class ReadTimeout(Timeout):62+ """The server did not send any data in the allotted amount of time."""63+64+65 class URLRequired(RequestException):66 """A valid URL is required to make a request."""67 68 22 unmodified linesmodified:requests/structures.py+1 added-1 removed
21 unmodified lines22 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::27 28 cid = CaseInsensitiveDict()29 cid['Accept'] = 'application/json'30 cid['aCCEPT'] == 'application/json' # True74 unmodified linesmodified:test_requests.py+49 added-2 removed
16 unmodified lines17 from requests.auth import HTTPDigestAuth, _basic_auth_str18 from requests.compat import (19 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)20 from requests.cookies import cookiejar_from_dict, morsel_to_cookie21-from requests.exceptions import InvalidURL, MissingSchema, ConnectionError21+from requests.exceptions import (InvalidURL, MissingSchema, ConnectTimeout,22+ ReadTimeout, ConnectionError, Timeout)23 from requests.models import PreparedRequest24 from requests.structures import CaseInsensitiveDict25 from requests.sessions import SessionRedirectMixin26 from requests.models import urlencode11 unmodified lines38 def u(s):39 return s.decode('unicode-escape')40 41 42+# Requests to this URL should always fail with a connection timeout (nothing43+# listening on that port)44+TARPIT = "http://10.255.255.1"45 HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')46 # Issue #1483: Make sure the URL always has a trailing slash47 HTTPBIN = HTTPBIN.rstrip('/') + '/'48 1262 unmodified lines1311 1312 class 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]1318 1319+ 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)1323 1324+ with pytest.raises(ValueError) as e:1325+ requests.get(httpbin('get'), timeout="foo")1326+ assert 'must be an int or float' in str(e)1327+1328+ def test_none_timeout(self):1329+ """ Check that you can set None as a valid timeout value.1330+1331+ 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 == 2001339+1340+ 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+ pass1346+1347+ 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)1354+1355+ 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+ pass1361+1362+1363 SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))1364 1365 1366 class RedirectSession(SessionRedirectMixin):115 unmodified lines