| 1 |
HTTPX allows you to register "event hooks" with the client, that are called |
| 2 |
every time a particular type of event takes place. |
| 3 |
|
| 4 |
There are currently two event hooks: |
| 5 |
|
| 6 |
* `request` - Called after a request is fully prepared, but before it is sent to the network. Passed the `request` instance. |
| 7 |
* `response` - Called after the response has been fetched from the network, but before it is returned to the caller. Passed the `response` instance. |
| 8 |
|
| 9 |
These allow you to install client-wide functionality such as logging, monitoring or tracing. |
| 10 |
|
| 11 |
```python |
| 12 |
def log_request(request): |
| 13 |
print(f"Request event hook: {request.method} {request.url} - Waiting for response") |
| 14 |
|
| 15 |
def log_response(response): |
| 16 |
request = response.request |
| 17 |
print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}") |
| 18 |
|
| 19 |
client = httpx.Client(event_hooks={'request': [log_request], 'response': [log_response]}) |
| 20 |
``` |
| 21 |
|
| 22 |
You can also use these hooks to install response processing code, such as this |
| 23 |
example, which creates a client instance that always raises `httpx.HTTPStatusError` |
| 24 |
on 4xx and 5xx responses. |
| 25 |
|
| 26 |
```python |
| 27 |
def raise_on_4xx_5xx(response): |
| 28 |
response.raise_for_status() |
| 29 |
|
| 30 |
client = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]}) |
| 31 |
``` |
| 32 |
|
| 33 |
!!! note |
| 34 |
Response event hooks are called before determining if the response body |
| 35 |
should be read or not. |
| 36 |
|
| 37 |
If you need access to the response body inside an event hook, you'll |
| 38 |
need to call `response.read()`, or for AsyncClients, `response.aread()`. |
| 39 |
|
| 40 |
The hooks are also allowed to modify `request` and `response` objects. |
| 41 |
|
| 42 |
```python |
| 43 |
def add_timestamp(request): |
| 44 |
request.headers['x-request-timestamp'] = datetime.now(tz=datetime.utc).isoformat() |
| 45 |
|
| 46 |
client = httpx.Client(event_hooks={'request': [add_timestamp]}) |
| 47 |
``` |
| 48 |
|
| 49 |
Event hooks must always be set as a **list of callables**, and you may register |
| 50 |
multiple event hooks for each type of event. |
| 51 |
|
| 52 |
As well as being able to set event hooks on instantiating the client, there |
| 53 |
is also an `.event_hooks` property, that allows you to inspect and modify |
| 54 |
the installed hooks. |
| 55 |
|
| 56 |
```python |
| 57 |
client = httpx.Client() |
| 58 |
client.event_hooks['request'] = [log_request] |
| 59 |
client.event_hooks['response'] = [log_response, raise_on_4xx_5xx] |
| 60 |
``` |
| 61 |
|
| 62 |
!!! note |
| 63 |
If you are using HTTPX's async support, then you need to be aware that |
| 64 |
hooks registered with `httpx.AsyncClient` MUST be async functions, |
| 65 |
rather than plain functions. |