Skip to content
Myr

Make safe_mode handle exceptions more consistently

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

authored by Ori Livneh · committed by Ori Livneh · parent 716d29c · Browse files · 2 files+48 added−37 removed
This commit

State

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

Diff stats

2 files+48 added−37 removed

  • other:+48 added−37 removed

2 files+48 added−37 removed

modified:requests/models.py+40 added-31 removed
16 unmodified lines
17from .structures import CaseInsensitiveDict18from .status_codes import codes19from .packages import oreos20from .auth import HTTPBasicAuth, HTTPProxyAuth21from .packages.urllib3.response import HTTPResponse22from .packages.urllib3.exceptions import MaxRetryError23from .packages.urllib3.exceptions import SSLError as _SSLError24from .packages.urllib3.exceptions import HTTPError as _HTTPError25from .packages.urllib3 import connectionpool, poolmanager26from .packages.urllib3.filepost import encode_multipart_formdata27from .exceptions import (27 Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError)28 ConnectionError, HTTPError, RequestException, Timeout, TooManyRedirects,29 URLRequired)30from .utils import (31 get_encoding_from_headers, stream_decode_response_unicode,32 decode_gzip, stream_decode_gzip, guess_filename, requote_path)33
138 unmodified lines
172173 # Save cookies in Response.174 response.cookies = cookies175176 # No exceptions were harmed in the making of this request.177 response.error = getattr(resp, 'error', None)178179 # Save original response for later.180 response.raw = resp181182 if is_error:
259 unmodified lines
442443 # Attach Cookie header to request.444 self.headers['Cookie'] = cookie_header445441 # If the request fails but exceptions are suppressed,442 # we'll build a blank response.443 r = None444446 try:447 # The inner try .. except re-raises certain exceptions as448 # internal exception types; the outer suppresses exceptions449 # when safe mode is set.450 try:446 # Send the request.447 r = conn.urlopen(448 method=self.method,449 url=self.path_url,450 body=body,451 headers=self.headers,452 redirect=False,453 assert_same_host=False,454 preload_content=False,455 decode_content=False,456 retries=self.config.get('max_retries', 0),457 timeout=self.timeout,458 )459 self.sent = True451 # Send the request.452 r = conn.urlopen(453 method=self.method,454 url=self.path_url,455 body=body,456 headers=self.headers,457 redirect=False,458 assert_same_host=False,459 preload_content=False,460 decode_content=False,461 retries=self.config.get('max_retries', 0),462 timeout=self.timeout,463 )464 self.sent = True465461462 except MaxRetryError, e:466 except MaxRetryError, e:463 if not self.config.get('safe_mode', False):467 raise ConnectionError(e)468466 except (_SSLError, _HTTPError), e:467 if not self.config.get('safe_mode', False):469 except (_SSLError, _HTTPError), e:470 raise Timeout('Request timed out.')471472 except RequestException, e:473 if self.config.get('safe_mode', False):474 # In safe mode, catch the exception and attach it to 475 # a blank urllib3.HTTPResponse object.476 r = HTTPResponse()477 r.error = e478 else:479 raise480481 self._build_response(r)482483 # Response manipulation hook.484 self.response = dispatch_hook('response', self.hooks, self.response)
84 unmodified lines
569 'The content for this response was already consumed'570 )571572 def generate():562 # self.raw can be None if we're in safe_mode and the request failed563 if self.raw is not None:564 while 1:565 chunk = self.raw.read(chunk_size)566 if not chunk:567 break568 yield chunk573 while 1:574 chunk = self.raw.read(chunk_size)575 if not chunk:576 break577 yield chunk578 self._content_consumed = True579580 gen = generate()581
127 unmodified lines
modified:test_requests.py+8 added-6 removed
617 unmodified lines
618 # Make sure iter_lines doesn't chop the trailing bit619 lines = '\n'.join(r.iter_lines())620 self.assertEqual(lines, quote)621622 def test_null_response(self):622 def test_safe_mode(self):623624 # Safe mode creates empty responses for failed requests.624 safe = requests.session(config=dict(safe_mode=True))625626 # Safe mode creates empty responses for failed requests.627 # Iterating on these responses should produce empty sequences627 r = requests.get('http://_/', config=dict(safe_mode=True))628 r = safe.get('http://_/')629 self.assertEquals(list(r.iter_lines()), [])630 self.assertIsInstance(r.error, requests.exceptions.ConnectionError)631630 r = requests.get('http://_/', config=dict(safe_mode=True))632 r = safe.get('http://_/')633 self.assertEquals(list(r.iter_content()), [])634 self.assertIsInstance(r.error, requests.exceptions.ConnectionError)635633 def test_timeout(self):634636 # When not in safe mode, should raise Timeout exception637 with self.assertRaises(requests.exceptions.Timeout):638 r = requests.get(httpbin('stream', '1000'), timeout=0.0001)639640 # In safe mode, should return a blank response641 r = requests.get(httpbin('stream', '1000'), timeout=0.0001,642 config=dict(safe_mode=True))643 self.assertIsNone(r.content)644 self.assertIsInstance(r.error, requests.exceptions.Timeout)645646647if __name__ == '__main__':648 unittest.main()