Skip to content
Myr

adding rewind for re-POST bodies

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

authored by Nate Prewitt · committed by Nate Prewitt · parent 9deb603 · Browse files · 6 files+51 added−5 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+51 added−5 removed

  • tests:+1 added−1 removed
  • other:+50 added−4 removed

6 files+51 added−5 removed

modified:requests/compat.py+2 added
48 unmodified lines
49 bytes = str50 str = unicode51 basestring = basestring52 numeric_types = (int, long, float)53 integer_types = (int, long)5455elif is_py3:56 from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag57 from urllib.request import parse_http_list, getproxies, proxy_bypass
6 unmodified lines
64 str = str65 bytes = bytes66 basestring = (str, bytes)67 numeric_types = (int, float)68 integer_types = (int,)
modified:requests/exceptions.py+2 added
98 unmodified lines
99100class RetryError(RequestException):101 """Custom retries logic failed"""102103class UnrewindableBodyError(RequestException):104 """Requests encountered an error when trying to rewind a body"""105106# Warnings107108
8 unmodified lines
modified:requests/models.py+14 added
289 unmodified lines
290 #: request body to send to the server.291 self.body = None292 #: dictionary of callback hooks, for internal usage.293 self.hooks = default_hooks()294 #: integer denoting starting position of a readable file-like body.295 self._body_position = None296297 def prepare(self, method=None, url=None, headers=None, files=None,298 data=None, params=None, auth=None, cookies=None, hooks=None, json=None):299 """Prepares the entire request with the given parameters."""
21 unmodified lines
321 p.headers = self.headers.copy() if self.headers is not None else None322 p._cookies = _copy_cookie_jar(self._cookies)323 p.body = self.body324 p.hooks = self.hooks325 p._body_position = self._body_position326 return p327328 def prepare_method(self, method):329 """Prepares the given HTTP method."""
119 unmodified lines
449450 if is_stream:451 body = data452453 if getattr(body, 'tell', None) is not None:454 # Record the current file position before reading.455 # This will allow us to rewind a file in the event456 # of a redirect.457 try:458 self._body_position = body.tell()459 except (IOError, OSError):460 # This differentiates from None, allowing us to catch461 # a failed `tell()` later when trying to rewind the body462 self._body_position = object()463464 if files:465 raise NotImplementedError('Streamed bodies and files are mutually exclusive.')466467 if length:
429 unmodified lines
modified:requests/sessions.py+13 added-1 removed
26 unmodified lines
27from .adapters import HTTPAdapter2829from .utils import (30 requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,31 get_auth_from_url31 get_auth_from_url, rewind_body32)3334from .status_codes import codes35
127 unmodified lines
163 # Rebuild auth and proxy information.164 proxies = self.rebuild_proxies(prepared_request, proxies)165 self.rebuild_auth(prepared_request, resp)166167 # A failed tell() sets `_body_position` to `object()`. This non-None168 # value ensures `rewindable` will be True, allowing us to raise an169 # UnrewindableBodyError, instead of hanging the connection.170 rewindable = (171 prepared_request._body_position is not None and172 ('Content-Length' in headers or 'Transfer-Encoding' in headers)173 )174175 # Attempt to rewind consumed file-like object.176 if rewindable:177 rewind_body(prepared_request)178179 # Override the original request.180 req = prepared_request181182 resp = self.send(
543 unmodified lines
modified:requests/utils.py+19 added-3 removed
21 unmodified lines
22from . import certs23# to_native_string is unused here, but imported here for backwards compatibility24from ._internal_utils import to_native_string25from .compat import parse_http_list as _parse_list_header26from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote,27 getproxies, proxy_bypass, urlunparse, basestring)26from .compat import (27 quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,28 proxy_bypass, urlunparse, basestring, integer_types)29from .cookies import RequestsCookieJar, cookiejar_from_dict30from .structures import CaseInsensitiveDict30from .exceptions import InvalidURL, InvalidHeader, FileModeWarning31from .exceptions import (32 InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)3334_hush_pyflakes = (RequestsCookieJar,)3536NETRC_FILES = ('.netrc', '_netrc')
775 unmodified lines
812813 netloc = netloc.rsplit('@', 1)[-1]814815 return urlunparse((scheme, netloc, path, params, query, ''))816817def rewind_body(prepared_request):818 """Move file pointer back to its recorded starting position819 so it can be read again on redirect.820 """821 body_seek = getattr(prepared_request.body, 'seek', None)822 if body_seek is not None and isinstance(prepared_request._body_position, integer_types):823 try:824 body_seek(prepared_request._body_position)825 except (IOError, OSError):826 raise UnrewindableBodyError("An error occured when rewinding request "827 "body for redirect.")828 else:829 raise UnrewindableBodyError("Unable to rewind request body for redirect.")
modified:tests/test_requests.py+1 added-1 removed
22 unmodified lines
23 cookiejar_from_dict, morsel_to_cookie, merge_cookies)24from requests.exceptions import (25 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,26 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,27 ProxyError, InvalidHeader)27 ProxyError, InvalidHeader, UnrewindableBodyError)28from requests.models import PreparedRequest29from requests.structures import CaseInsensitiveDict30from requests.sessions import SessionRedirectMixin31from requests.models import urlencode
1932 unmodified lines