Skip to content
Myr

redirects work!

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

authored by Kenneth Reitz · committed by Kenneth Reitz · parent 4a01272 · Browse files · 2 files+118 added−12 removed
This commit

State

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

Diff stats

2 files+118 added−12 removed

  • other:+118 added−12 removed

2 files+118 added−12 removed

modified:requests/models.py+3 added
573 unmodified lines
574 if http_error_msg:575 http_error = HTTPError(http_error_msg)576 http_error.response = self577 raise http_error578579 def close(self):580 return self.raw.release_conn()
modified:requests/sessions.py+115 added-12 removed
16 unmodified lines
17from .hooks import dispatch_hook18from .utils import header_expand, from_key_val_list19from .packages.urllib3.poolmanager import PoolManager202121from .compat import urlparse, urljoin22from .adapters import HTTPAdapter2324from .utils import requote_uri2526from .status_codes import codes27REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)28293031def merge_kwargs(local_kwarg, default_kwarg):32 """Merges kwarg dictionaries.3334 If a local key in the dictionary is set to None, it will be removed.
26 unmodified lines
6162 return kwargs63646558class Session(object):66class SessionMixin(object):6768 def resolve_redirects(self, resp, req, prefetch=True, timeout=None, verify=True, cert=None):69 """Receives a Response. Returns a generator of Responses."""7071 print resp72 print req73 print resp.headers['location']74 print resp.status_code7576 # ((resp.status_code is codes.see_other))77 while (('location' in resp.headers and resp.status_code in REDIRECT_STATI)):7879 resp.content # Consume socket so it can be released8081 # if not len(history) < self.config.get('max_redirects'):82 # raise TooManyRedirects()8384 # Release the connection back into the pool.85 resp.close()8687 # history.append(r)8889 url = resp.headers['location']9091 # Handle redirection without scheme (see: RFC 1808 Section 4)92 if url.startswith('//'):93 parsed_rurl = urlparse(resp.url)94 url = '%s:%s' % (parsed_rurl.scheme, url)9596 # Facilitate non-RFC2616-compliant 'location' headers97 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')98 if not urlparse(url).netloc:99 url = urljoin(resp.url,100 # Compliant with RFC3986, we percent101 # encode the url.102 requote_uri(url))103104 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4105 if resp.status_code is codes.see_other:106 method = 'GET'107 else:108 method = req.method109110 # Do what the browsers do, despite standards...111 if resp.status_code in (codes.moved, codes.found) and req.method == 'POST':112 method = 'GET'113114 if (resp.status_code == 303) and req.method != 'HEAD':115 method = 'GET'116117 # Remove the cookie headers that were sent.118 # headers = req.headers119 # try:120 # del headers['Cookie']121 # except KeyError:122 # pass123124 resp = self.request(125 url=url,126 method=method,127 params=req.params,128 auth=req.auth,129 cookies=req.cookies,130 allow_redirects=False,131 prefetch=prefetch,132 timeout=timeout,133 verify=verify,134 cert=cert135 )136137 yield resp138139140141142143144145146147class Session(SessionMixin):148 """A Requests session."""149150 __attrs__ = [151 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',
102 unmodified lines
254 prep = req.prepare()255256 # TODO: prepare cookies.257169 return self.send(prep)258 resp = self.send(prep)259260 if allow_redirects:261 gen = self.resolve_redirects(resp, req, prefetch, timeout, verify, cert)262263 history = [r for r in gen]264265 print history266267 return resp268269270271272273274275 def get(self, url, **kwargs):276 """Sends a GET request. Returns :class:`Response` object.277278 :param url: URL for the new :class:`Request` object.279 :param \*\*kwargs: Optional arguments that ``request`` takes.280 """281282 kwargs.setdefault('allow_redirects', True)180 return self.request('get', url, **kwargs)283 return self.request('GET', url, **kwargs)284285 def options(self, url, **kwargs):286 """Sends a OPTIONS request. Returns :class:`Response` object.287
1 unmodified line
289 :param \*\*kwargs: Optional arguments that ``request`` takes.290 """291292 kwargs.setdefault('allow_redirects', True)190 return self.request('options', url, **kwargs)293 return self.request('OPTIONS', url, **kwargs)294295 def head(self, url, **kwargs):296 """Sends a HEAD request. Returns :class:`Response` object.297
1 unmodified line
299 :param \*\*kwargs: Optional arguments that ``request`` takes.300 """301302 kwargs.setdefault('allow_redirects', False)200 return self.request('head', url, **kwargs)303 return self.request('HEAD', url, **kwargs)304305 def post(self, url, data=None, **kwargs):306 """Sends a POST request. Returns :class:`Response` object.307
1 unmodified line
309 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.310 :param \*\*kwargs: Optional arguments that ``request`` takes.311 """312210 return self.request('post', url, data=data, **kwargs)313 return self.request('POST', url, data=data, **kwargs)314315 def put(self, url, data=None, **kwargs):316 """Sends a PUT request. Returns :class:`Response` object.317
1 unmodified line
319 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.320 :param \*\*kwargs: Optional arguments that ``request`` takes.321 """322220 return self.request('put', url, data=data, **kwargs)323 return self.request('PUT', url, data=data, **kwargs)324325 def patch(self, url, data=None, **kwargs):326 """Sends a PATCH request. Returns :class:`Response` object.327
1 unmodified line
329 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.330 :param \*\*kwargs: Optional arguments that ``request`` takes.331 """332230 return self.request('patch', url, data=data, **kwargs)333 return self.request('PATCH', url, data=data, **kwargs)334335 def delete(self, url, **kwargs):336 """Sends a DELETE request. Returns :class:`Response` object.337338 :param url: URL for the new :class:`Request` object.339 :param \*\*kwargs: Optional arguments that ``request`` takes.340 """341239 return self.request('delete', url, **kwargs)342 return self.request('DELETE', url, **kwargs)343241 def send(self, request):344 def send(self, request, prefetch=True, timeout=None, verify=True, cert=None):345 """Send a given PreparedRequest."""346 adapter = HTTPAdapter()244 r = adapter.send(request)347 r = adapter.send(request, prefetch, timeout, verify, cert)348 return r349350 def __getstate__(self):351 return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)
12 unmodified lines