Skip to content
Myr

Merge pull request #4352 from alexwlchan/hooks-on-sessions

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Add something to the docs about hooks on Session()

authored by Nate Prewitt · committed by GitHub · parents c4c031f, c5ed41e · Browse files · 1 file+26 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+26 added−2 removed

  • other:+26 added−2 removed

1 file+26 added−2 removed

modified:docs/user/advanced.rst+26 added-2 removed
434 unmodified lines
435You can assign a hook function on a per-request basis by passing a436``{hook_name: callback_function}`` dictionary to the ``hooks`` request437parameter::438439 hooks=dict(response=print_url)439 hooks={'response': print_url}440441That ``callback_function`` will receive a chunk of data as its first442argument.443
7 unmodified lines
451If the callback function returns a value, it is assumed that it is to452replace the data that was passed in. If the function doesn't return453anything, nothing else is effected.454455::456457 def record_hook(r, *args, **kwargs):458 r.hook_called = True459 return r460461Let's print some request method arguments at runtime::462457 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))463 >>> requests.get('http://httpbin.org', hooks={'response': print_url})464 http://httpbin.org465 <Response [200]>466467You can add multiple hooks to a single request. Let's call two hooks at once::468469 >>> r = requests.get('http://httpbin.org', hooks={'response': [print_url, record_hook]})470 >>> r.hook_called471 True472473You can also add hooks to a ``Session`` instance. Any hooks you add will then474be called on every request made to the session. For example::475476 >>> s = requests.Session()477 >>> s.hooks['response'].append(print_url)478 >>> s.get('http://httpbin.org')479 http://httpbin.org480 <Response [200]>481482A ``Session`` can have multiple hooks, which will be called in the order483they are added.484485.. _custom-auth:486487Custom Authentication488---------------------
548 unmodified lines