Custom RedirectHandler and .history support.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Closes #23
authored by Kenneth Reitz · committed by Kenneth Reitz · parent 35beda2 · Browse files · 2 files·+69 added−17 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+69 added−17 removed
- other:+69 added−17 removed
Provenance
- Commit
cd8ce63- Tree
d6e8608- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
35beda2
2 files changed+69 added−17 removed
modified:requests/models.py+53 added-14 removed
13 unmodified lines14 15 from urllib2 import HTTPError16 from urlparse import urlparse17 18-from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPDigestAuthHandler18+from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler19 from .structures import CaseInsensitiveDict20 from .packages.poster.encode import multipart_encode21 from .packages.poster.streaminghttp import register_openers, get_handlers22 6 unmodified lines29 30 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')31 32 def __init__(self, url=None, headers=dict(), files=None, method=None,33- data=dict(), auth=None, cookiejar=None, timeout=None):33+ data=dict(), auth=None, cookiejar=None, timeout=None, redirect=True):34 35 socket.setdefaulttimeout(timeout)36 37 self.url = url38 self.headers = headers39 self.files = files40 self.method = method41- self.data = {}41+ self.data = dict()42+ self.redirect = redirect43 44 # self.data = {}45 if hasattr(data, 'items'):46 for (k, v) in data.items():54 unmodified lines101 auth_manager.add_auth(self.url, self.auth)102 103 _handlers.append(self.auth.handler)104 105+106+ _handlers.append(HTTPRedirectHandler)107+ # print _handlers108+ # print '^^'109+ # print '!'110+111 if not _handlers:112 return urllib2.urlopen113 114+ if self.data or self.files:107- _handlers.extend(get_handlers())115+ _handlers.extend(get_handlers())116+117 opener = urllib2.build_opener(*_handlers)118 119 if self.headers:120 # Allow default headers in the opener to be overloaded8 unmodified lines129 130 def _build_response(self, resp):131 """Build internal Response object from given response."""132 124- self.response.status_code = getattr(resp, 'code', None)133+ def build(resp):134 126- try:127- self.response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))128- self.response.content = resp.read()129- except AttributeError:130- pass135+ response = Response()136+ response.status_code = getattr(resp, 'code', None)137 132- if self.response.headers['content-encoding'] == 'gzip':138 try:134- self.response.content = zlib.decompress(self.response.content, 16+zlib.MAX_WBITS)135- except zlib.error:139+ response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))140+ response.content = resp.read()141+ except AttributeError:142 pass143 138- self.response.url = getattr(resp, 'url', None)144+ if response.headers['content-encoding'] == 'gzip':145+ try:146+ response.content = zlib.decompress(response.content, 16+zlib.MAX_WBITS)147+ except zlib.error:148+ pass149 150+ response.url = getattr(resp, 'url', None)151 152+ return response153+154+155+ history = []156+157+ r = build(resp)158+159+ if self.redirect:160+161+ while 'location' in r.headers:162+163+ history.append(r)164+165+ url = r.headers['location']166+167+ request = Request(168+ url, self.headers, self.files, self.method,169+ self.data, self.auth, self.cookiejar, redirect=False170+ )171+ request.send()172+ r = request.response173+174+ r.history = history175+176+ self.response = r177+178+179 @staticmethod180 def _build_url(url, data=None):181 """Build URLs."""182 81 unmodified lines264 self.url = None265 self.ok = False266 self.error = None267 self.cached = False268+ self.history = []269 270 271 def __repr__(self):272 return '<Response [%s]>' % (self.status_code)199 unmodified linesmodified:requests/monkeys.py+16 added-3 removed
1-# -*- coding: utf-8 -*-1+#-*- coding: utf-8 -*-2 3 """4 requests.monkeys5 ~~~~~~~~~~~~~~~~20 unmodified lines26 27 return urllib2.Request.get_method(self)28 29 30+class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):31+32+ def http_error_301(self, req, fp, code, msg, headers):33+ # print "Cookie Manip Right Here"34+ # print 'HEY'35+ pass36+ # return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)37+38+ http_error_302 = http_error_303 = http_error_307 = http_error_30139+40+41+42 class HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):31- # from mercurial43 44 def __init__(self, *args, **kwargs):45 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)46 self.retried_req = None8 unmodified lines55 # Reset the retry counter once for each request.56 if req is not self.retried_req:57 self.retried_req = req58 self.retried = 059+60 return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(49- self, auth_header, host, req, headers)61+ self, auth_header, host, req, headers62+ )63 64 65 66 class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):28 unmodified lines