* initial attempt at `get_redirect_target`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* removing the `i` from the redirect detection while-loop
authored by jonathan vanasco · committed by jonathan vanasco · parent ad65b0c · Browse files · 4 files·+70 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+70 added−11 removed
- tests:+43 added−0 removed
- other:+27 added−11 removed
Provenance
- Commit
70f31a3- Tree
6ab5ae2- Author
jonathan vanasco <jonathan@2xlp.com>- Committer
jonathan vanasco <jonathan@2xlp.com>- Parent
ad65b0c
4 files changed+70 added−11 removed
modified:requests/sessions.py+16 added-11 removed
84 unmodified lines85 return merge_setting(request_hooks, session_hooks, dict_class)86 87 88 class SessionRedirectMixin(object):89+90+ def get_redirect_target(self, resp):91+ """Receives a Response. Returns a redirect URI or ``None``"""92+ if resp.is_redirect:93+ return resp.headers['location']94+ return None95+96 def resolve_redirects(self, resp, req, stream=False, timeout=None,97 verify=True, cert=None, proxies=None, **adapter_kwargs):98 """Receives a Response. Returns a generator of Responses."""99 93- i = 0100 hist = [] # keep track of history101 96- while resp.is_redirect:102+ url = self.get_redirect_target(resp)103+ while url:104 prepared_request = req.copy()105 99- if i > 0:100- # Update history and keep track of redirects.101- hist.append(resp)102- new_hist = list(hist)103- resp.history = new_hist106+ # Update history and keep track of redirects.107+ # resp.history must ignore the original request in this loop108+ hist.append(resp)109+ resp.history = hist[1:]110 111 try:112 resp.content # Consume socket so it can be released113 except (ChunkedEncodingError, ContentDecodingError, RuntimeError):114 resp.raw.read(decode_content=False)115 110- if i >= self.max_redirects:116+ if len(resp.history) >= self.max_redirects:117 raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp)118 119 # Release the connection back into the pool.120 resp.close()121 116- url = resp.headers['location']117-122 # Handle redirection without scheme (see: RFC 1808 Section 4)123 if url.startswith('//'):124 parsed_rurl = urlparse(resp.url)125 url = '%s:%s' % (parsed_rurl.scheme, url)69 unmodified lines195 )196 197 extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)198 195- i += 1199+ # extract redirect url, if any, for the next loop200+ url = self.get_redirect_target(resp)201 yield resp202 203 def rebuild_auth(self, prepared_request, response):204 """When being redirected we may want to strip authentication from the526 unmodified linesmodified:tests/test_requests.py+43 added
1738 unmodified lines1739 prepared_request = r.prepare()1740 assert 'Transfer-Encoding' in prepared_request.headers1741 assert 'Content-Length' not in prepared_request.headers1742 1743+ def test_custom_redirect_mixin(self, httpbin):1744+ """Tests a custom mixin to overwrite ``get_redirect_target``.1745 1746+ Ensures a subclassed ``requests.Session`` can handle a certain type of1747+ malformed redirect responses.1748+1749+ 1. original request receives a proper response: 302 redirect1750+ 2. following the redirect, a malformed response is given:1751+ status code = HTTP 2001752+ location = alternate url1753+ 3. the custom session catches the edge case and follows the redirect1754+ """1755+ url_final = httpbin('html')1756+ querystring_malformed = urlencode({'location': url_final})1757+ url_redirect_malformed = httpbin('response-headers?%s' % querystring_malformed)1758+ querystring_redirect = urlencode({'url': url_redirect_malformed})1759+ url_redirect = httpbin('redirect-to?%s' % querystring_redirect)1760+ urls_test = [url_redirect,1761+ url_redirect_malformed,1762+ url_final,1763+ ]1764+1765+ class CustomRedirectSession(requests.Session):1766+ def get_redirect_target(self, resp):1767+ # default behavior1768+ if resp.is_redirect:1769+ return resp.headers['location']1770+ # edge case - check to see if 'location' is in headers anyways1771+ location = resp.headers.get('location')1772+ if location and (location != resp.url):1773+ return location1774+ return None1775+1776+ session = CustomRedirectSession()1777+ r = session.get(urls_test[0])1778+ assert len(r.history) == 21779+ assert r.status_code == 2001780+ assert r.history[0].status_code == 3021781+ assert r.history[0].is_redirect1782+ assert r.history[1].status_code == 2001783+ assert not r.history[1].is_redirect1784+ assert r.url == urls_test[2]1785+1786+1787 class TestCaseInsensitiveDict:1788 1789 @pytest.mark.parametrize(1790 'cid', (548 unmodified linesmodified:AUTHORS.rst+2 added
175 unmodified lines176 - Casey Davidson (`@davidsoncasey <https://github.com/davidsoncasey>`_)177 - Andrii Soldatenko (`@a_soldatenko <https://github.com/andriisoldatenko>`_)178 - Moinuddin Quadri <moin18@gmail.com> (`@moin18 <https://github.com/moin18>`_)179 - Matt Kohl (`@mattkohl <https://github.com/mattkohl>`_)180+- Jonathan Vanasco (`@jvanasco <https://github.com/jvanasco>`_)181+modified:HISTORY.rst+9 added
1 unmodified line2 3 Release History4 ---------------5 6+**Unreleased**7++++++++++++++++++++8+9+- The behavior of ``SessionRedirectMixin`` was slightly altered.10+ ``resolve_redirects`` will now detect a redirect by calling11+ ``get_redirect_target(response)`` instead of directly12+ querying ``Response.is_redirect`` and ``Response.headers['location']``.13+ Advanced users will be able to process malformed redirects more easily.14+15 2.13.0 (2017-01-24)16 +++++++++++++++++++17 18 **Features**1299 unmodified lines