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
Provenance
- Commit
e1615e0- Tree
ecca78c- Author
Ori Livneh <ori.livneh@gmail.com>- Committer
Ori Livneh <ori.livneh@gmail.com>- Parent
716d29c
2 files changed+48 added−37 removed
modified:requests/models.py+40 added-31 removed
16 unmodified lines17 from .structures import CaseInsensitiveDict18 from .status_codes import codes19 from .packages import oreos20 from .auth import HTTPBasicAuth, HTTPProxyAuth21+from .packages.urllib3.response import HTTPResponse22 from .packages.urllib3.exceptions import MaxRetryError23 from .packages.urllib3.exceptions import SSLError as _SSLError24 from .packages.urllib3.exceptions import HTTPError as _HTTPError25 from .packages.urllib3 import connectionpool, poolmanager26 from .packages.urllib3.filepost import encode_multipart_formdata27 from .exceptions import (27- Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError)28+ ConnectionError, HTTPError, RequestException, Timeout, TooManyRedirects,29+ URLRequired)30 from .utils import (31 get_encoding_from_headers, stream_decode_response_unicode,32 decode_gzip, stream_decode_gzip, guess_filename, requote_path)33 138 unmodified lines172 173 # Save cookies in Response.174 response.cookies = cookies175 176+ # No exceptions were harmed in the making of this request.177+ response.error = getattr(resp, 'error', None)178+179 # Save original response for later.180 response.raw = resp181 182 if is_error:259 unmodified lines442 443 # Attach Cookie header to request.444 self.headers['Cookie'] = cookie_header445 441- # If the request fails but exceptions are suppressed,442- # we'll build a blank response.443- r = None444-446 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 = True465 461-462- except MaxRetryError, e:466+ except MaxRetryError, e:463- if not self.config.get('safe_mode', False):467 raise ConnectionError(e)468 466- except (_SSLError, _HTTPError), e:467- if not self.config.get('safe_mode', False):469+ except (_SSLError, _HTTPError), e:470 raise Timeout('Request timed out.')471 472+ 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+ raise480+481 self._build_response(r)482 483 # Response manipulation hook.484 self.response = dispatch_hook('response', self.hooks, self.response)84 unmodified lines569 'The content for this response was already consumed'570 )571 572 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 = True579 580 gen = generate()581 127 unmodified linesmodified:test_requests.py+8 added-6 removed
617 unmodified lines618 # Make sure iter_lines doesn't chop the trailing bit619 lines = '\n'.join(r.iter_lines())620 self.assertEqual(lines, quote)621 622- def test_null_response(self):622+ def test_safe_mode(self):623 624- # Safe mode creates empty responses for failed requests.624+ safe = requests.session(config=dict(safe_mode=True))625 626+ # 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)631 630- 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)635 633- def test_timeout(self):634-636 # 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)639 640 # 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)645 646 647 if __name__ == '__main__':648 unittest.main()