From 2dc556e0825bf3a235140c5af6b473945ebf4ab8 Mon Sep 17 00:00:00 2001 From: Luca De Vitis Date: Tue, 23 Aug 2011 15:06:22 +0200 Subject: [PATCH] Added multiple hooks support. --- requests/api.py | 10 +++++----- requests/hooks.py | 26 +++++++++++++++++--------- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/requests/api.py b/requests/api.py index 0928d8c8..9acc1e5f 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 2938029b..2fa97d0b 100644 --- a/requests/hooks.py +++ b/requests/hooks.py @@ -23,18 +23,26 @@ Available hooks: """ import warnings +from collections import Iterable +def dispatch_hooks(key, hooks, hook_data): + """Dispatches multiple hooks on a given piece of data. -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: + :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 +