Skip to content
Myr

Merge pull request #3846 from jvanasco/feature-pluggable_handling

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

initial attempt at `get_redirect_target`

authored by Kenneth Reitz · committed by GitHub · parents ad65b0c, 70f31a3 · 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

4 files+70 added−11 removed

modified:requests/sessions.py+16 added-11 removed
84 unmodified lines
85 return merge_setting(request_hooks, session_hooks, dict_class)868788class SessionRedirectMixin(object):8990 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 None9596 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."""9993 i = 0100 hist = [] # keep track of history10196 while resp.is_redirect:102 url = self.get_redirect_target(resp)103 while url:104 prepared_request = req.copy()10599 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:]110111 try:112 resp.content # Consume socket so it can be released113 except (ChunkedEncodingError, ContentDecodingError, RuntimeError):114 resp.raw.read(decode_content=False)115110 if i >= self.max_redirects:116 if len(resp.history) >= self.max_redirects:117 raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp)118119 # Release the connection back into the pool.120 resp.close()121116 url = resp.headers['location']117122 # 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 lines
195 )196197 extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)198195 i += 1199 # extract redirect url, if any, for the next loop200 url = self.get_redirect_target(resp)201 yield resp202203 def rebuild_auth(self, prepared_request, response):204 """When being redirected we may want to strip authentication from the
526 unmodified lines
modified:tests/test_requests.py+43 added
1738 unmodified lines
1739 prepared_request = r.prepare()1740 assert 'Transfer-Encoding' in prepared_request.headers1741 assert 'Content-Length' not in prepared_request.headers17421743 def test_custom_redirect_mixin(self, httpbin):1744 """Tests a custom mixin to overwrite ``get_redirect_target``.17451746 Ensures a subclassed ``requests.Session`` can handle a certain type of1747 malformed redirect responses.17481749 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 ]17641765 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 None17751776 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]178517861787class TestCaseInsensitiveDict:17881789 @pytest.mark.parametrize(1790 'cid', (
548 unmodified lines
modified:AUTHORS.rst+2 added
175 unmodified lines
176- 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 line
23Release History4---------------56**Unreleased**7+++++++++++++++++++89- 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.14152.13.0 (2017-01-24)16+++++++++++++++++++1718**Features**
1299 unmodified lines