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
Provenance
- Commit
f72684e- Tree
54fbe14- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
87e40d1- Parent 2
522d37c
7 files changed+168 added−6 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')773 unmodified lines810 811 netloc = netloc.rsplit('@', 1)[-1]812 813 return urlunparse((scheme, netloc, path, params, query, ''))814+815+def 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 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 urlencode132 unmodified lines164 assert r.status_code == 200165 assert r.history[0].status_code == 302166 assert r.history[0].is_redirect167 168+ 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'174+175+ 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')182+183 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 lines1400 pass1401 r3 = next(rg)1402 assert not r3.is_redirect1403 1404+ 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 None1409+1410+ 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'1416+1417+ # the data has all been read1418+ assert prep.body.read() == b''1419+1420+ # rewind it back1421+ requests.utils.rewind_body(prep)1422+ assert prep.body.read() == b'the data'1423+1424+ 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'1431+1432+ # the data has all been read1433+ assert prep.body.read() == b''1434+1435+ # rewind it back1436+ requests.utils.rewind_body(prep)1437+ assert prep.body.read() == b'data'1438+1439+ def test_rewind_body_no_seek(self):1440+ class BadFileObj:1441+ def __init__(self, data):1442+ self.data = data1443+1444+ def tell(self):1445+ return 01446+1447+ def __iter__(self):1448+ return1449+1450+ data = BadFileObj('the data')1451+ s = requests.Session()1452+ prep = requests.Request('GET', 'http://example.com', data=data).prepare()1453+ assert prep._body_position == 01454+1455+ with pytest.raises(UnrewindableBodyError) as e:1456+ requests.utils.rewind_body(prep)1457+1458+ assert 'Unable to rewind request body' in str(e)1459+1460+ def test_rewind_body_failed_seek(self):1461+ class BadFileObj:1462+ def __init__(self, data):1463+ self.data = data1464+1465+ def tell(self):1466+ return 01467+1468+ def seek(self, pos):1469+ raise OSError()1470+1471+ def __iter__(self):1472+ return1473+1474+ data = BadFileObj('the data')1475+ s = requests.Session()1476+ prep = requests.Request('GET', 'http://example.com', data=data).prepare()1477+ assert prep._body_position == 01478+1479+ with pytest.raises(UnrewindableBodyError) as e:1480+ requests.utils.rewind_body(prep)1481+1482+ assert 'error occured when rewinding request body' in str(e)1483+1484+ def test_rewind_body_failed_tell(self):1485+ class BadFileObj:1486+ def __init__(self, data):1487+ self.data = data1488+1489+ def tell(self):1490+ raise OSError()1491+1492+ def __iter__(self):1493+ return1494+1495+ 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 None1499+1500+ with pytest.raises(UnrewindableBodyError) as e:1501+ requests.utils.rewind_body(prep)1502+1503+ assert 'Unable to rewind request body' in str(e)1504+1505 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 = False581 unmodified linesmodified:requirements.txt+1 added-1 removed
2 unmodified lines3 coverage==4.0.34 decorator==4.0.95 docutils==0.126 Flask==0.10.17-httpbin==0.4.17+httpbin==0.5.08 itsdangerous==0.249 Jinja2==2.810 MarkupSafe==0.2311 py==1.4.3113 unmodified lines