Skip to content

Commit

Permalink
Facilitate for multiple hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
jgorset committed Jan 21, 2012
1 parent 5bff8e3 commit 7647e52
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 4 deletions.
13 changes: 9 additions & 4 deletions requests/hooks.py
Expand Up @@ -31,10 +31,15 @@ def dispatch_hook(key, hooks, hook_data):
hooks = hooks or dict()

if key in hooks:
try:
return hooks.get(key).__call__(hook_data) or hook_data
hooks = hooks.get(key)

except Exception:
traceback.print_exc()
if hasattr(hooks, '__call__'):
hooks = [hooks]

for hook in hooks:
try:
hook_data = hook(hook_data) or hook_data
except Exception:
traceback.print_exc()

return hook_data
59 changes: 59 additions & 0 deletions test_requests.py
Expand Up @@ -516,6 +516,65 @@ def test_session_persistent_headers(self):

self.assertEqual(r2.status_code, 200)

def test_single_hook(self):

def add_foo_header(args):
if not args.get('headers'):
args['headers'] = {}

args['headers'].update({
'X-Foo': 'foo'
})

return args

for service in SERVICES:
url = service('headers')

response = requests.get(
url = url,
hooks = {
'args': add_foo_header
}
)

assert 'foo' in response.content

def test_multiple_hooks(self):

def add_foo_header(args):
if not args.get('headers'):
args['headers'] = {}

args['headers'].update({
'X-Foo': 'foo'
})

return args

def add_bar_header(args):
if not args.get('headers'):
args['headers'] = {}

args['headers'].update({
'X-Bar': 'bar'
})

return args

for service in SERVICES:
url = service('headers')

response = requests.get(
url = url,
hooks = {
'args': [add_foo_header, add_bar_header]
}
)

assert 'foo' in response.content
assert 'bar' in response.content

def test_session_persistent_cookies(self):

s = requests.session()
Expand Down

0 comments on commit 7647e52

Please sign in to comment.