Skip to content
Myr

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamable

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

Rewind readable body before POST redirect

authored by Cory Benfield · committed by GitHub · parents 87e40d1, 522d37c · Browse files · 7 files+168 added−6 removed
This commit

State

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

Diff stats

7 files+168 added−6 removed

  • tests:+117 added−1 removed
  • other:+51 added−5 removed

7 files+168 added−6 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')
773 unmodified lines
810811 netloc = netloc.rsplit('@', 1)[-1]812813 return urlunparse((scheme, netloc, path, params, query, ''))814815def rewind_body(prepared_request):816 """Move file pointer back to its recorded starting position817 so it can be read again on redirect.818 """819 body_seek = getattr(prepared_request.body, 'seek', None)820 if body_seek is not None and isinstance(prepared_request._body_position, integer_types):821 try:822 body_seek(prepared_request._body_position)823 except (IOError, OSError):824 raise UnrewindableBodyError("An error occured when rewinding request "825 "body for redirect.")826 else:827 raise UnrewindableBodyError("Unable to rewind request body for redirect.")
modified:tests/test_requests.py+117 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
132 unmodified lines
164 assert r.status_code == 200165 assert r.history[0].status_code == 302166 assert r.history[0].is_redirect167168 def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):169 r = requests.post(httpbin('redirect-to'), data='test', params={'url': 'post', 'status_code': 307})170 assert r.status_code == 200171 assert r.history[0].status_code == 307172 assert r.history[0].is_redirect173 assert r.json()['data'] == 'test'174175 def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):176 byte_str = b'test'177 r = requests.post(httpbin('redirect-to'), data=io.BytesIO(byte_str), params={'url': 'post', 'status_code': 307})178 assert r.status_code == 200179 assert r.history[0].status_code == 307180 assert r.history[0].is_redirect181 assert r.json()['data'] == byte_str.decode('utf-8')182183 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):184 try:185 requests.get(httpbin('relative-redirect', '50'))186 except TooManyRedirects as e:
1213 unmodified lines
1400 pass1401 r3 = next(rg)1402 assert not r3.is_redirect14031404 def test_prepare_body_position_non_stream(self):1405 data = b'the data'1406 s = requests.Session()1407 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1408 assert prep._body_position is None14091410 def test_rewind_body(self):1411 data = io.BytesIO(b'the data')1412 s = requests.Session()1413 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1414 assert prep._body_position == 01415 assert prep.body.read() == b'the data'14161417 # the data has all been read1418 assert prep.body.read() == b''14191420 # rewind it back1421 requests.utils.rewind_body(prep)1422 assert prep.body.read() == b'the data'14231424 def test_rewind_partially_read_body(self):1425 data = io.BytesIO(b'the data')1426 s = requests.Session()1427 data.read(4) # read some data1428 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1429 assert prep._body_position == 41430 assert prep.body.read() == b'data'14311432 # the data has all been read1433 assert prep.body.read() == b''14341435 # rewind it back1436 requests.utils.rewind_body(prep)1437 assert prep.body.read() == b'data'14381439 def test_rewind_body_no_seek(self):1440 class BadFileObj:1441 def __init__(self, data):1442 self.data = data14431444 def tell(self):1445 return 014461447 def __iter__(self):1448 return14491450 data = BadFileObj('the data')1451 s = requests.Session()1452 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1453 assert prep._body_position == 014541455 with pytest.raises(UnrewindableBodyError) as e:1456 requests.utils.rewind_body(prep)14571458 assert 'Unable to rewind request body' in str(e)14591460 def test_rewind_body_failed_seek(self):1461 class BadFileObj:1462 def __init__(self, data):1463 self.data = data14641465 def tell(self):1466 return 014671468 def seek(self, pos):1469 raise OSError()14701471 def __iter__(self):1472 return14731474 data = BadFileObj('the data')1475 s = requests.Session()1476 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1477 assert prep._body_position == 014781479 with pytest.raises(UnrewindableBodyError) as e:1480 requests.utils.rewind_body(prep)14811482 assert 'error occured when rewinding request body' in str(e)14831484 def test_rewind_body_failed_tell(self):1485 class BadFileObj:1486 def __init__(self, data):1487 self.data = data14881489 def tell(self):1490 raise OSError()14911492 def __iter__(self):1493 return14941495 data = BadFileObj('the data')1496 s = requests.Session()1497 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1498 assert prep._body_position is not None14991500 with pytest.raises(UnrewindableBodyError) as e:1501 requests.utils.rewind_body(prep)15021503 assert 'Unable to rewind request body' in str(e)15041505 def _patch_adapter_gzipped_redirect(self, session, url):1506 adapter = session.get_adapter(url=url)1507 org_build_response = adapter.build_response1508 self._patched_response = False
581 unmodified lines
modified:requirements.txt+1 added-1 removed
2 unmodified lines
3coverage==4.0.34decorator==4.0.95docutils==0.126Flask==0.10.17httpbin==0.4.17httpbin==0.5.08itsdangerous==0.249Jinja2==2.810MarkupSafe==0.2311py==1.4.31
13 unmodified lines