Added multiple hooks support.
authorLuca De Vitis <luca@monkeython.com>
Tue, 23 Aug 2011 13:06:22 +0000 (15:06 +0200)
committerLuca De Vitis <luca@monkeython.com>
Tue, 23 Aug 2011 13:06:22 +0000 (15:06 +0200)
requests/api.py
requests/hooks.py

index 0928d8c82af5177c311f78c87be465c3c5315be1..9acc1e5f8d0fbad6bbde139d09ce67e1bae5c1e7 100644 (file)
@@ -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
 
index 2938029b6c06aea1f85ccf0f33c4b17da28b60c7..2fa97d0b9168a1eb91d7b270c5df4bf413ad2472 100644 (file)
@@ -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
+