event-hooks.md
This file
Path
docs/advanced/event-hooks.md
65 lines · 2.4 KiB · Markdown
Last changed by
Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
History of this fileTake it
Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 1–65why, one step back1HTTPX allows you to register "event hooks" with the client, that are called2every time a particular type of event takes place.34There are currently two event hooks:56* `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.89These allow you to install client-wide functionality such as logging, monitoring or tracing.1011```python12def log_request(request):13 print(f"Request event hook: {request.method} {request.url} - Waiting for response")1415def log_response(response):16 request = response.request17 print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")1819client = httpx.Client(event_hooks={'request': [log_request], 'response': [log_response]})20```2122You can also use these hooks to install response processing code, such as this23example, which creates a client instance that always raises `httpx.HTTPStatusError`24on 4xx and 5xx responses.2526```python27def raise_on_4xx_5xx(response):28 response.raise_for_status()2930client = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]})31```3233!!! note34 Response event hooks are called before determining if the response body35 should be read or not.3637 If you need access to the response body inside an event hook, you'll38 need to call `response.read()`, or for AsyncClients, `response.aread()`.3940The hooks are also allowed to modify `request` and `response` objects.4142```python43def add_timestamp(request):44 request.headers['x-request-timestamp'] = datetime.now(tz=datetime.utc).isoformat()4546client = httpx.Client(event_hooks={'request': [add_timestamp]})47```4849Event hooks must always be set as a **list of callables**, and you may register50multiple event hooks for each type of event.5152As well as being able to set event hooks on instantiating the client, there53is also an `.event_hooks` property, that allows you to inspect and modify54the installed hooks.5556```python57client = httpx.Client()58client.event_hooks['request'] = [log_request]59client.event_hooks['response'] = [log_response, raise_on_4xx_5xx]60```6162!!! note63 If you are using HTTPX's async support, then you need to be aware that64 hooks registered with `httpx.AsyncClient` MUST be async functions,65 rather than plain functions.