mirror of
https://github.com/kennethreitz/requests.git
synced 2026-06-05 22:50:18 +00:00
Added multiple hooks support.
This commit is contained in:
+5
-5
@@ -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
|
||||
|
||||
|
||||
+17
-9
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user