From: Luca De Vitis Date: Tue, 23 Aug 2011 13:06:22 +0000 (+0200) Subject: Added multiple hooks support. X-Git-Tag: v0.8.0~94^2~4^2~9 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=2dc556e0825bf3a235140c5af6b473945ebf4ab8;p=services%2Fpython-requests.git Added multiple hooks support. --- diff --git a/requests/api.py b/requests/api.py index 0928d8c..9acc1e5 100644 --- a/requests/api.py +++ b/requests/api.py @@ -14,7 +14,7 @@ This module impliments the Requests API. import config from .models import Request, Response, AuthObject from .status_codes import codes -from .hooks import dispatch_hook +from .hooks import dispatch_hooks from .utils import cookiejar_from_dict from urlparse import urlparse @@ -63,21 +63,21 @@ def request(method, url, ) # Arguments manipulation hook. - args = dispatch_hook('args', hooks, args) + args = dispatch_hooks('args', hooks, args) r = Request(**args) # Pre-request hook. - r = dispatch_hook('pre_request', hooks, r) + r = dispatch_hooks('pre_request', hooks, r) # Send the HTTP Request. r.send() # Post-request hook. - r = dispatch_hook('post_request', hooks, r) + r = dispatch_hooks('post_request', hooks, r) # Response manipulation hook. - r.response = dispatch_hook('response', hooks, r.response) + r.response = dispatch_hooks('response', hooks, r.response) return r.response diff --git a/requests/hooks.py b/requests/hooks.py index 2938029..2fa97d0 100644 --- a/requests/hooks.py +++ b/requests/hooks.py @@ -23,18 +23,26 @@ Available hooks: """ import warnings - - -def dispatch_hook(key, hooks, hook_data): - """Dipatches a hook dictionary on a given peice of data.""" - - hooks = hooks or dict() - - if key in hooks: +from collections import Iterable + +def dispatch_hooks(key, hooks, hook_data): + """Dispatches multiple hooks on a given piece of data. + + :param key: the hooks group to lookup + :type key: str + :param hooks: the hooks dictionary. The value of each key can be a callable + object, or a list of callable objects. + :type hooks: dict + :param hook_data: the object on witch the hooks should be applied + :type hook_data: object + """ + hook_list = hooks.get(key, []) if hooks else [] + dispatching = hook_list if isinstance(hook_list, Iterable) else [hook_list] + for hook in dispatching: try: - return hooks.get(key).__call__(hook_data) or hook_data - + # hook must be a callable + hook_data = hook(hook_data) except Exception, why: warnings.warn(str(why)) - return hook_data +