Merge pull request #604 from joshimhoff/develop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
New implementation of safe_mode.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 2d328d8, db43eb4 · Browse files · 5 files·+69 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+69 added−52 removed
- other:+69 added−52 removed
Provenance
- Commit
3d2d072- Tree
d7da6b7- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
2d328d8- Parent 2
db43eb4
5 files changed+69 added−52 removed
modified:requests/api.py+2 added
10 unmodified lines11 12 """13 14 from . import sessions15+from .safe_mode import catch_exceptions_if_in_safe_mode16 17+@catch_exceptions_if_in_safe_mode18 def request(method, url, **kwargs):19 """Constructs and sends a :class:`Request <Request>`.20 Returns :class:`Response <Response>` object.21 98 unmodified linesmodified:requests/cookies.py+4 added-7 removed
92 unmodified lines93 :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)101 102 def 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 linesmodified:requests/models.py+24 added-45 removed
202 unmodified lines203 # Save cookies in Response.204 response.cookies = self.cookies205 206 # 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)209 210 # No exceptions were harmed in the making of this request.211 response.error = getattr(resp, 'error', None)212 371 unmodified lines584 # Pre-send hook.585 r = dispatch_hook('pre_send', self.hooks, self)586 self.__dict__.update(r.__dict__)587 588+ # 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 = True604 610- except MaxRetryError as e:611- raise ConnectionError(e)605+ except MaxRetryError as e:606+ raise ConnectionError(e)607 613- 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)611 617- raise Timeout('Request timed out.')612+ raise Timeout('Request timed out.')613 619- 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- raise627-614 # 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- raise616 617 # Response manipulation hook.618 self.response = dispatch_hook('response', self.hooks, self.response)619 212 unmodified linesadded:requests/safe_mode.py+38 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.safe_mode5+~~~~~~~~~~~~6+7+This module contains a decorator that implements safe_mode.8+9+:copyright: (c) 2012 by Kenneth Reitz.10+:license: ISC, see LICENSE for more details.11+12+"""13+14+from .models import Response15+from .packages.urllib3.response import HTTPResponse16+from .exceptions import RequestException, ConnectionError, HTTPError17+import socket18+19+def catch_exceptions_if_in_safe_mode(function):20+ """New implementation of safe_mode. We catch all exceptions at the API level21+ and then return a blank Response object with the error field filled. This decorator22+ wraps request() in api.py.23+ """24+ 25+ def wrapped(method, url, **kwargs):26+ # if save_mode, we catch exceptions and fill error field27+ if (kwargs.get('config') and kwargs.get('config').get('safe_mode')) or (kwargs.get('session') 28+ and kwargs.get('session').config.get('safe_mode')):29+ try:30+ return function(method, url, **kwargs)31+ except (RequestException, ConnectionError, HTTPError, socket.timeout) as e:32+ r = Response()33+ r.error = e34+ r.raw = HTTPResponse() # otherwise, tests fail35+ r.status_code = 0 # with this status_code, content returns None36+ return r37+ return function(method, url, **kwargs)38+ return wrappedmodified:AUTHORS.rst+1 added
98 unmodified lines99 - Miguel Turner100 - Rohan Jain (crodjer)101 - Justin Barber <barber.justin@gmail.com>102 - Roman Haritonov <@reclosedev>103+- Josh Imhoff <joshimhoff13@gmail.com>