hooks and things
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 2c5b020 · Browse files · 3 files·+57 added−140 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+57 added−140 removed
- other:+57 added−140 removed
Provenance
- Commit
377078b- Tree
21d21f5- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
2c5b020
3 files changed+57 added−140 removed
modified:requests/auth.py+2 added-125 removed
95 unmodified lines96 r.url, r.headers, _ = self.client.sign(unicode(r.full_url),97 unicode(r.method),98 None,99 r.headers)100- elif (decoded_body is not None and 100+ elif (decoded_body is not None and101 contenttype == CONTENT_TYPE_FORM_URLENCODED):102 # If the Content-Type header is urlencoded and there are no103 # illegal characters in the body, assume that the content actually104 # is urlencoded, and so should be part of the signature.163 unmodified lines268 # If we have a saved nonce, skip the 401269 if self.last_nonce:270 r.headers['Authorization'] = self.build_digest_header(r.method, r.url)271 r.register_hook('response', self.handle_401)272- return r273-274-275-def _negotiate_value(r):276- """Extracts the gssapi authentication token from the appropriate header"""277-278- authreq = r.headers.get('www-authenticate', None)279-280- if authreq:281- rx = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)282- mo = rx.search(authreq)283- if mo:284- return mo.group(1)285-286- return None287-288-289-class HTTPKerberosAuth(AuthBase):290- """Attaches HTTP GSSAPI/Kerberos Authentication to the given Request object."""291- def __init__(self, require_mutual_auth=True):292- if k is None:293- raise Exception("Kerberos libraries unavailable")294- self.context = None295- self.require_mutual_auth = require_mutual_auth296-297- def generate_request_header(self, r):298- """Generates the gssapi authentication token with kerberos"""299-300- host = urlparse(r.url).netloc301- tail, _, head = host.rpartition(':')302- domain = tail if tail else head303-304- result, self.context = k.authGSSClientInit("HTTP@%s" % domain)305-306- if result < 1:307- raise Exception("authGSSClientInit failed")308-309- result = k.authGSSClientStep(self.context, _negotiate_value(r))310-311- if result < 0:312- raise Exception("authGSSClientStep failed")313-314- response = k.authGSSClientResponse(self.context)315-316- return "Negotiate %s" % response317-318- def authenticate_user(self, r):319- """Handles user authentication with gssapi/kerberos"""320-321- auth_header = self.generate_request_header(r)322- log.debug("authenticate_user(): Authorization header: %s" % auth_header)323- r.request.headers['Authorization'] = auth_header324- r.request.send(anyway=True)325- _r = r.request.response326- _r.history.append(r)327- log.debug("authenticate_user(): returning %s" % _r)328- return _r329-330- def handle_401(self, r):331- """Handles 401's, attempts to use gssapi/kerberos authentication"""332-333- log.debug("handle_401(): Handling: 401")334- if _negotiate_value(r) is not None:335- _r = self.authenticate_user(r)336- log.debug("handle_401(): returning %s" % _r)337- return _r338- else:339- log.debug("handle_401(): Kerberos is not supported")340- log.debug("handle_401(): returning %s" % r)341- return r342-343- def handle_other(self, r):344- """Handles all responses with the exception of 401s.345-346- This is necessary so that we can authenticate responses if requested"""347-348- log.debug("handle_other(): Handling: %d" % r.status_code)349- self.deregister(r)350- if self.require_mutual_auth:351- if _negotiate_value(r) is not None:352- log.debug("handle_other(): Authenticating the server")353- _r = self.authenticate_server(r)354- log.debug("handle_other(): returning %s" % _r)355- return _r356- else:357- log.error("handle_other(): Mutual authentication failed")358- raise Exception("Mutual authentication failed")359- else:360- log.debug("handle_other(): returning %s" % r)361- return r362-363- def authenticate_server(self, r):364- """Uses GSSAPI to authenticate the server"""365-366- log.debug("authenticate_server(): Authenticate header: %s" % _negotiate_value(r))367- result = k.authGSSClientStep(self.context, _negotiate_value(r))368- if result < 1:369- raise Exception("authGSSClientStep failed")370- _r = r.request.response371- log.debug("authenticate_server(): returning %s" % _r)372- return _r373-374- def handle_response(self, r):375- """Takes the given response and tries kerberos-auth, as needed."""376-377- if r.status_code == 401:378- _r = self.handle_401(r)379- log.debug("handle_response returning %s" % _r)380- return _r381- else:382- _r = self.handle_other(r)383- log.debug("handle_response returning %s" % _r)384- return _r385-386- log.debug("handle_response returning %s" % r)387- return r388-389- def deregister(self, r):390- """Deregisters the response handler"""391- r.request.deregister_hook('response', self.handle_response)392-393- def __call__(self, r):394- r.register_hook('response', self.handle_response)395- return r272+ return rmodified:requests/hooks.py+8 added-1 removed
12 unmodified lines13 14 """15 16 17-HOOKS = ('response')17+HOOKS = ['response']18+19+def default_hooks():20+ hooks = {}21+ for event in HOOKS:22+ hooks[event] = []23+ return hooks24+25 # TODO: response is the only one26 27 def dispatch_hook(key, hooks, hook_data):28 """Dispatches a hook dictionary on a given piece of data."""15 unmodified linesmodified:requests/models.py+47 added-14 removed
7 unmodified lines8 """9 10 # import os11 # import socket12-# import collections12+import collections13 import logging14 15 # from datetime import datetime16 from io import BytesIO17 18-from .hooks import dispatch_hook, HOOKS18+from .hooks import dispatch_hook, default_hooks19 from .structures import CaseInsensitiveDict20 from .status_codes import codes21 22 from .auth import HTTPBasicAuth, HTTPProxyAuth22 unmodified lines45 46 log = logging.getLogger(__name__)47 48 49-class RequestMixin(object):49+class RequestEncodingMixin(object):50 51 @property52 def path_url(self):53 """Build the path URL to use."""88 unmodified lines142 143 return body, content_type144 145 146-class Request(object):146+class RequestHooksMixin(object):147+ def register_hook(self, event, hook):148+ """Properly register a hook."""149+ print self150+ print event151+ print hook152+ if isinstance(hook, collections.Callable):153+ self.hooks[event].append(hook)154+ elif hasattr(hook, '__iter__'):155+ self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))156+157+ def deregister_hook(self, event, hook):158+ """Deregister a previously registered hook.159+ Returns True if the hook existed, False if not.160+ """161+162+ try:163+ self.hooks[event].remove(hook)164+ return True165+ except ValueError:166+ return False167+168+169+class Request(RequestHooksMixin):170 """A user-created :class:`Request <Request>` object."""171 def __init__(self,172 method=None,173 url=None,3 unmodified lines177 params=dict(),178 auth=None,179 cookies=None,180 timeout=None,158- allow_redirects=False,159- proxies=None,160- hooks=None,181+ hooks=None):161- prefetch=True,162- verify=None,163- cert=None):182 183+ # Default empty dicts for dict params.184+ data = [] if data is None else data185+ files = [] if files is None else files186+ headers = {} if headers is None else headers187+ params = {} if params is None else params188+ hooks = {} if hooks is None else hooks189+190+ self.hooks = default_hooks()191+ for (k, v) in list(hooks.items()):192+ self.register_hook(event=k, hook=v)193+194 self.method = method195 self.url = url196 self.headers = headers197 self.files = files198 self.data = data199 self.params = params200 self.auth = auth201 self.cookies = cookies173- self.allow_redirects = allow_redirects174- self.proxies = proxies202+ # self.allow_redirects = allow_redirects203+ # self.proxies = proxies204 self.hooks = hooks205 206 def __repr__(self):207 return '<Request [%s]>' % (self.method)11 unmodified lines219 220 return p221 222 194-class PreparedRequest(RequestMixin):223+class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):224 """The :class:`PreparedRequest <PreparedRequest>` object."""225 226 def __init__(self):227 self.method = None3 unmodified lines231 self.params = None232 self.auth = None233 self.allow_redirects = None234 self.proxies = None206- self.hooks = None235+ self.hooks = default_hooks()236 237 def __repr__(self):238 return '<PreparedRequest [%s]>' % (self.method)239 101 unmodified lines341 342 def prepare_auth(self, auth):343 """Prepares the given HTTP auth data."""344 if auth:345+ # print auth346 if isinstance(auth, tuple) and len(auth) == 2:347 # special-case basic HTTP auth348 auth = HTTPBasicAuth(*auth)349 350 # Allow auth to make its changes.351 r = auth(self)352+ # print r353+ # print r.__dict__354+ # print self.__dict__355 356 # Update self to reflect the auth changes.357 self.__dict__.update(r.__dict__)358 249 unmodified lines