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
Provenance
- Commit
0bee888- Tree
fe5f36e- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
4a01272
2 files changed+118 added−12 removed
modified:requests/models.py+3 added
573 unmodified lines574 if http_error_msg:575 http_error = HTTPError(http_error_msg)576 http_error.response = self577 raise http_error578+579+ def close(self):580+ return self.raw.release_conn()modified:requests/sessions.py+115 added-12 removed
16 unmodified lines17 from .hooks import dispatch_hook18 from .utils import header_expand, from_key_val_list19 from .packages.urllib3.poolmanager import PoolManager20 21-21+from .compat import urlparse, urljoin22 from .adapters import HTTPAdapter23 24+from .utils import requote_uri25+26+from .status_codes import codes27+REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)28+29+30+31 def merge_kwargs(local_kwarg, default_kwarg):32 """Merges kwarg dictionaries.33 34 If a local key in the dictionary is set to None, it will be removed.26 unmodified lines61 62 return kwargs63 64 65+58-class Session(object):66+class SessionMixin(object):67+68+ def resolve_redirects(self, resp, req, prefetch=True, timeout=None, verify=True, cert=None):69+ """Receives a Response. Returns a generator of Responses."""70+71+ print resp72+ print req73+ print resp.headers['location']74+ print resp.status_code75+76+ # ((resp.status_code is codes.see_other))77+ while (('location' in resp.headers and resp.status_code in REDIRECT_STATI)):78+79+ resp.content # Consume socket so it can be released80+81+ # if not len(history) < self.config.get('max_redirects'):82+ # raise TooManyRedirects()83+84+ # Release the connection back into the pool.85+ resp.close()86+87+ # history.append(r)88+89+ url = resp.headers['location']90+91+ # 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)95+96+ # 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))103+104+ # 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.method109+110+ # Do what the browsers do, despite standards...111+ if resp.status_code in (codes.moved, codes.found) and req.method == 'POST':112+ method = 'GET'113+114+ if (resp.status_code == 303) and req.method != 'HEAD':115+ method = 'GET'116+117+ # Remove the cookie headers that were sent.118+ # headers = req.headers119+ # try:120+ # del headers['Cookie']121+ # except KeyError:122+ # pass123+124+ 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+ )136+137+ yield resp138+139+140+141+142+143+144+145+146+147+class Session(SessionMixin):148 """A Requests session."""149 150 __attrs__ = [151 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',102 unmodified lines254 prep = req.prepare()255 256 # TODO: prepare cookies.257 169- return self.send(prep)258+ resp = self.send(prep)259 260+ if allow_redirects:261+ gen = self.resolve_redirects(resp, req, prefetch, timeout, verify, cert)262 263+ history = [r for r in gen]264+265+ print history266+267+ return resp268+269+270+271+272+273+274+275 def get(self, url, **kwargs):276 """Sends a GET request. Returns :class:`Response` object.277 278 :param url: URL for the new :class:`Request` object.279 :param \*\*kwargs: Optional arguments that ``request`` takes.280 """281 282 kwargs.setdefault('allow_redirects', True)180- return self.request('get', url, **kwargs)283+ return self.request('GET', url, **kwargs)284 285 def options(self, url, **kwargs):286 """Sends a OPTIONS request. Returns :class:`Response` object.287 1 unmodified line289 :param \*\*kwargs: Optional arguments that ``request`` takes.290 """291 292 kwargs.setdefault('allow_redirects', True)190- return self.request('options', url, **kwargs)293+ return self.request('OPTIONS', url, **kwargs)294 295 def head(self, url, **kwargs):296 """Sends a HEAD request. Returns :class:`Response` object.297 1 unmodified line299 :param \*\*kwargs: Optional arguments that ``request`` takes.300 """301 302 kwargs.setdefault('allow_redirects', False)200- return self.request('head', url, **kwargs)303+ return self.request('HEAD', url, **kwargs)304 305 def post(self, url, data=None, **kwargs):306 """Sends a POST request. Returns :class:`Response` object.307 1 unmodified line309 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.310 :param \*\*kwargs: Optional arguments that ``request`` takes.311 """312 210- return self.request('post', url, data=data, **kwargs)313+ return self.request('POST', url, data=data, **kwargs)314 315 def put(self, url, data=None, **kwargs):316 """Sends a PUT request. Returns :class:`Response` object.317 1 unmodified line319 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.320 :param \*\*kwargs: Optional arguments that ``request`` takes.321 """322 220- return self.request('put', url, data=data, **kwargs)323+ return self.request('PUT', url, data=data, **kwargs)324 325 def patch(self, url, data=None, **kwargs):326 """Sends a PATCH request. Returns :class:`Response` object.327 1 unmodified line329 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.330 :param \*\*kwargs: Optional arguments that ``request`` takes.331 """332 230- return self.request('patch', url, data=data, **kwargs)333+ return self.request('PATCH', url, data=data, **kwargs)334 335 def delete(self, url, **kwargs):336 """Sends a DELETE request. Returns :class:`Response` object.337 338 :param url: URL for the new :class:`Request` object.339 :param \*\*kwargs: Optional arguments that ``request`` takes.340 """341 239- return self.request('delete', url, **kwargs)342+ return self.request('DELETE', url, **kwargs)343 241- 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 r349 350 def __getstate__(self):351 return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)12 unmodified lines