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
Provenance
- Commit
40402cd- Tree
19aa7a6- Author
Nate Prewitt <Nate.Prewitt@gmail.com>- Committer
Nate Prewitt <Nate.Prewitt@gmail.com>- Parent
9deb603
6 files changed+51 added−5 removed
modified:requests/compat.py+2 added
48 unmodified lines49 bytes = str50 str = unicode51 basestring = basestring52 numeric_types = (int, long, float)53+ integer_types = (int, long)54 55 elif 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_bypass6 unmodified lines64 str = str65 bytes = bytes66 basestring = (str, bytes)67 numeric_types = (int, float)68+ integer_types = (int,)modified:requests/exceptions.py+2 added
98 unmodified lines99 100 class RetryError(RequestException):101 """Custom retries logic failed"""102 103+class UnrewindableBodyError(RequestException):104+ """Requests encountered an error when trying to rewind a body"""105 106 # Warnings107 108 8 unmodified linesmodified:requests/models.py+14 added
289 unmodified lines290 #: 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 = None296 297 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 lines321 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 p327 328 def prepare_method(self, method):329 """Prepares the given HTTP method."""119 unmodified lines449 450 if is_stream:451 body = data452 453+ 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()463+464 if files:465 raise NotImplementedError('Streamed bodies and files are mutually exclusive.')466 467 if length:429 unmodified linesmodified:requests/sessions.py+13 added-1 removed
26 unmodified lines27 from .adapters import HTTPAdapter28 29 from .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 )33 34 from .status_codes import codes35 127 unmodified lines163 # Rebuild auth and proxy information.164 proxies = self.rebuild_proxies(prepared_request, proxies)165 self.rebuild_auth(prepared_request, resp)166 167+ # 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+ )174+175+ # Attempt to rewind consumed file-like object.176+ if rewindable:177+ rewind_body(prepared_request)178+179 # Override the original request.180 req = prepared_request181 182 resp = self.send(543 unmodified linesmodified:requests/utils.py+19 added-3 removed
21 unmodified lines22 from . import certs23 # to_native_string is unused here, but imported here for backwards compatibility24 from ._internal_utils import to_native_string25 from .compat import parse_http_list as _parse_list_header26-from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote,27- getproxies, proxy_bypass, urlunparse, basestring)26+from .compat import (27+ quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,28+ proxy_bypass, urlunparse, basestring, integer_types)29 from .cookies import RequestsCookieJar, cookiejar_from_dict30 from .structures import CaseInsensitiveDict30-from .exceptions import InvalidURL, InvalidHeader, FileModeWarning31+from .exceptions import (32+ InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)33 34 _hush_pyflakes = (RequestsCookieJar,)35 36 NETRC_FILES = ('.netrc', '_netrc')775 unmodified lines812 813 netloc = netloc.rsplit('@', 1)[-1]814 815 return urlunparse((scheme, netloc, path, params, query, ''))816+817+def 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 lines23 cookiejar_from_dict, morsel_to_cookie, merge_cookies)24 from requests.exceptions import (25 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,26 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,27- ProxyError, InvalidHeader)27+ ProxyError, InvalidHeader, UnrewindableBodyError)28 from requests.models import PreparedRequest29 from requests.structures import CaseInsensitiveDict30 from requests.sessions import SessionRedirectMixin31 from requests.models import urlencode1932 unmodified lines