Skip to content
Myr

New implementation of safe_mode. Now, we throw exceptions in models.py regardless of safe_mode. We catch those exceptions at the API level and return a blank Response. See safe_mode.py for details.

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

authored by Josh Imhoff · committed by Josh Imhoff · parent 2d328d8 · Browse files · 5 files+68 added−52 removed
This commit

State

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

Diff stats

5 files+68 added−52 removed

  • other:+68 added−52 removed

5 files+68 added−52 removed

modified:requests/api.py+2 added
10 unmodified lines
1112"""1314from . import sessions15from .safe_mode import catch_exceptions_if_in_safe_mode1617@catch_exceptions_if_in_safe_mode18def request(method, url, **kwargs):19 """Constructs and sends a :class:`Request <Request>`.20 Returns :class:`Response <Response>` object.21
98 unmodified lines
modified:requests/cookies.py+4 added-7 removed
92 unmodified lines
93 :param request: our own requests.Request object94 :param response: urllib3.HTTPResponse object95 """96 # the _original_response field is the wrapped httplib.HTTPResponse object,97 # and in safe mode, it may be None if the request didn't actually complete.98 # in that case, just skip the cookie extraction.99 if response._original_response is not None:100 req = MockRequest(request)101 # pull out the HTTPMessage with the headers and put it in the mock:102 res = MockResponse(response._original_response.msg)103 jar.extract_cookies(res, req)97 req = MockRequest(request)98 # pull out the HTTPMessage with the headers and put it in the mock:99 res = MockResponse(response._original_response.msg)100 jar.extract_cookies(res, req)101102def get_cookie_header(jar, request):103 """Produce an appropriate Cookie header string to be sent with `request`, or None."""104 r = MockRequest(request)
157 unmodified lines
modified:requests/models.py+24 added-45 removed
202 unmodified lines
203 # Save cookies in Response.204 response.cookies = self.cookies205206 # Save cookies in Session.207 # (in safe mode, cookies may be None if the request didn't succeed)208 if self.cookies is not None:209 for cookie in self.cookies:210 self.session.cookies.set_cookie(cookie)207 for cookie in self.cookies:208 self.session.cookies.set_cookie(cookie)209210 # No exceptions were harmed in the making of this request.211 response.error = getattr(resp, 'error', None)212
371 unmodified lines
584 # Pre-send hook.585 r = dispatch_hook('pre_send', self.hooks, self)586 self.__dict__.update(r.__dict__)587588 # catch urllib3 exceptions and throw Requests exceptions589 try:591 # The inner try .. except re-raises certain exceptions as592 # internal exception types; the outer suppresses exceptions593 # when safe mode is set.594 try:595 # Send the request.596 r = conn.urlopen(597 method=self.method,598 url=self.path_url,599 body=body,600 headers=self.headers,601 redirect=False,602 assert_same_host=False,603 preload_content=False,604 decode_content=False,605 retries=self.config.get('max_retries', 0),606 timeout=self.timeout,607 )608 self.sent = True590 # Send the request.591 r = conn.urlopen(592 method=self.method,593 url=self.path_url,594 body=body,595 headers=self.headers,596 redirect=False,597 assert_same_host=False,598 preload_content=False,599 decode_content=False,600 retries=self.config.get('max_retries', 0),601 timeout=self.timeout,602 )603 self.sent = True604610 except MaxRetryError as e:611 raise ConnectionError(e)605 except MaxRetryError as e:606 raise ConnectionError(e)607613 except (_SSLError, _HTTPError) as e:614 if self.verify and isinstance(e, _SSLError):615 raise SSLError(e)608 except (_SSLError, _HTTPError) as e:609 if self.verify and isinstance(e, _SSLError):610 raise SSLError(e)611617 raise Timeout('Request timed out.')612 raise Timeout('Request timed out.')613619 except RequestException as e:620 if self.config.get('safe_mode', False):621 # In safe mode, catch the exception and attach it to622 # a blank urllib3.HTTPResponse object.623 r = HTTPResponse()624 r.error = e625 else:626 raise627614 # build_response can throw TooManyRedirects629 try:630 self._build_response(r)615 self._build_response(r)631 except RequestException as e:632 if self.config.get('safe_mode', False):633 # In safe mode, catch the exception634 self.response.error = e635 else:636 raise616617 # Response manipulation hook.618 self.response = dispatch_hook('response', self.hooks, self.response)619
212 unmodified lines
added:requests/safe_mode.py+37 added
1# -*- coding: utf-8 -*-23"""4requests.safe_mode5~~~~~~~~~~~~67This module contains a decorator that implements safe_mode.89:copyright: (c) 2012 by Kenneth Reitz.10:license: ISC, see LICENSE for more details.1112"""1314from .models import Response15from .exceptions import RequestException, ConnectionError, HTTPError16from .packages.urllib3.response import HTTPResponse1718def catch_exceptions_if_in_safe_mode(function):19 """New implementation of safe_mode. We catch all exceptions at the API level20 and then return a blank Response object with the error field filled. This decorator21 wraps request() in api.py.22 """23 24 def wrapped(method, url, **kwargs):25 # if save_mode, we catch exceptions and fill error field26 if (kwargs.get('config') and kwargs.get('config').get('safe_mode')) or (kwargs.get('session') 27 and kwargs.get('session').config.get('safe_mode')):28 try:29 return function(method, url, **kwargs)30 except (RequestException, ConnectionError, HTTPError) as e:31 r = Response()32 r.error = e33 r.raw = HTTPResponse() # otherwise, tests fail34 r.status_code = 0 # with this status_code, content returns None35 return r36 return function(method, url, **kwargs)37 return wrapped
modified:AUTHORS.rst+1 added
98 unmodified lines
99- Miguel Turner100- Rohan Jain (crodjer)101- Justin Barber <barber.justin@gmail.com>102- Roman Haritonov <@reclosedev>103- Josh Imhoff <joshimhoff13@gmail.com>