Skip to content
Myr

docs: slightly clarify event hooks (#1645)

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

* Be more specific about when the hooks are called * Explicitly mention and demonstrate that hooks are allowed to modify requests See https://github.com/encode/httpx/discussions/1637

authored by K900 · committed by GitHub · parent 9b17671 · Browse files · 1 file+12 added−3 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+12 added−3 removed

  • other:+12 added−3 removed

1 file+12 added−3 removed

modified:docs/advanced.md+12 added-3 removed
226 unmodified lines
227every time a particular type of event takes place.228229There are currently two event hooks:230231* `request` - Called once a request is about to be sent. Passed the `request` instance.232* `response` - Called once the response has been returned. Passed the `response` instance.231* `request` - Called after a request is fully prepared, but before it is sent to the network. Passed the `request` instance.232* `response` - Called after the response has been fetched from the network, but before it is returned to the caller. Passed the `response` instance.233234These allow you to install client-wide functionality such as logging and monitoring.234These allow you to install client-wide functionality such as logging, monitoring or tracing.235236```python237def log_request(request):238 print(f"Request event hook: {request.method} {request.url} - Waiting for response")
15 unmodified lines
254255client = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]})256```257258The hooks are also allowed to modify `request` and `response` objects.259260```python261def add_timestamp(request):262 request.headers['x-request-timestamp'] = datetime.now(tz=datetime.utc).isoformat()263 264client = httpx.Client(event_hooks={'request': [add_timestamp]})265```266267Event hooks must always be set as a **list of callables**, and you may register268multiple event hooks for each type of event.269270As well as being able to set event hooks on instantiating the client, there
914 unmodified lines