Skip to content
Myr

Event hooks (#1246)

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

* Add EventHooks internal datastructure * Add support for 'request' and 'response' event hooks * Support Client.event_hooks property * Handle exceptions raised by response event hooks * Docs for event hooks * Only support 'request' and 'response' event hooks * Add event_hooks to top-level API * Event hooks * Formatting * Formatting * Fix up event hooks test * Add test case to confirm that redirects/event hooks don't currently play together correctly * Refactor test cases * Make response.request clear in response event hooks docs * Drop merge marker * Request event hook runs as soon as we have an auth-constructed request

authored by Tom Christie · committed by GitHub · parent d0fe113 · Browse files · 4 files+294 added−0 removed
This commit

State

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

Diff stats

4 files+294 added−0 removed

  • tests:+198 added−0 removed
  • other:+96 added−0 removed

4 files+294 added−0 removed

modified:docs/advanced.md+52 added
219 unmodified lines
220 response = client.send(request)221 ...222```223224## Event Hooks225226HTTPX allows you to register "event hooks" with the client, that are called227every 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.233234These allow you to install client-wide functionality such as logging and monitoring.235236```python237def log_request(request):238 print(f"Request event hook: {request.method} {request.url} - Waiting for response")239240def log_response(response):241 request = response.request242 print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")243244client = httpx.Client(event_hooks={'request': [log_request], 'response': [log_response]})245```246247You can also use these hooks to install response processing code, such as this248example, which creates a client instance that always raises `httpx.HTTPStatusError`249on 4xx and 5xx responses.250251```python252def raise_on_4xx_5xx(response):253 response.raise_for_status()254255client = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]})256```257258Event hooks must always be set as a **list of callables**, and you may register259multiple event hooks for each type of event.260261As well as being able to set event hooks on instantiating the client, there262is also an `.event_hooks` property, that allows you to inspect and modify263the installed hooks.264265```python266client = httpx.Client()267client.event_hooks['request'] = [log_request]268client.event_hooks['response'] = [log_response, raise_for_status]269```270271!!! note272 If you are using HTTPX's async support, then you need to be aware that273 hooks registered with `httpx.AsyncClient` MUST be async functions,274 rather than plain functions.275276## Monitoring download progress277278If you need to monitor download progress of large responses, you can use response streaming and inspect the `response.num_bytes_downloaded` property.279
780 unmodified lines
modified:httpx/_client.py+44 added
72 unmodified lines
73 headers: HeaderTypes = None,74 cookies: CookieTypes = None,75 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,76 max_redirects: int = DEFAULT_MAX_REDIRECTS,77 event_hooks: typing.Dict[str, typing.List[typing.Callable]] = None,78 base_url: URLTypes = "",79 trust_env: bool = True,80 ):81 event_hooks = {} if event_hooks is None else event_hooks8283 self._base_url = self._enforce_trailing_slash(URL(base_url))8485 self._auth = self._build_auth(auth)86 self._params = QueryParams(params)87 self.headers = Headers(headers)88 self._cookies = Cookies(cookies)89 self._timeout = Timeout(timeout)90 self.max_redirects = max_redirects91 self._event_hooks = {92 "request": list(event_hooks.get("request", [])),93 "response": list(event_hooks.get("response", [])),94 }95 self._trust_env = trust_env96 self._netrc = NetRCInfo()97 self._is_closed = True98
41 unmodified lines
140 def timeout(self, timeout: TimeoutTypes) -> None:141 self._timeout = Timeout(timeout)142143 @property144 def event_hooks(self) -> typing.Dict[str, typing.List[typing.Callable]]:145 return self._event_hooks146147 @event_hooks.setter148 def event_hooks(149 self, event_hooks: typing.Dict[str, typing.List[typing.Callable]]150 ) -> None:151 self._event_hooks = {152 "request": list(event_hooks.get("request", [])),153 "response": list(event_hooks.get("response", [])),154 }155156 @property157 def auth(self) -> typing.Optional[Auth]:158 """159 Authentication class used when none is passed at the request-level.160
390 unmodified lines
551 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,552 limits: Limits = DEFAULT_LIMITS,553 pool_limits: Limits = None,554 max_redirects: int = DEFAULT_MAX_REDIRECTS,555 event_hooks: typing.Dict[str, typing.List[typing.Callable]] = None,556 base_url: URLTypes = "",557 transport: httpcore.SyncHTTPTransport = None,558 app: typing.Callable = None,559 trust_env: bool = True,
4 unmodified lines
564 headers=headers,565 cookies=cookies,566 timeout=timeout,567 max_redirects=max_redirects,568 event_hooks=event_hooks,569 base_url=base_url,570 trust_env=trust_env,571 )572
187 unmodified lines
760 response.read()761 finally:762 response.close()763764 try:765 for hook in self._event_hooks["response"]:766 hook(response)767 except Exception:768 response.close()769 raise770771 return response772773 def _send_handling_auth(774 self,
5 unmodified lines
780 ) -> Response:781 auth_flow = auth.sync_auth_flow(request)782 request = next(auth_flow)783784 for hook in self._event_hooks["request"]:785 hook(request)786787 while True:788 response = self._send_handling_redirects(789 request,790 timeout=timeout,
393 unmodified lines
1184 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,1185 limits: Limits = DEFAULT_LIMITS,1186 pool_limits: Limits = None,1187 max_redirects: int = DEFAULT_MAX_REDIRECTS,1188 event_hooks: typing.Dict[str, typing.List[typing.Callable]] = None,1189 base_url: URLTypes = "",1190 transport: httpcore.AsyncHTTPTransport = None,1191 app: typing.Callable = None,1192 trust_env: bool = True,
4 unmodified lines
1197 headers=headers,1198 cookies=cookies,1199 timeout=timeout,1200 max_redirects=max_redirects,1201 event_hooks=event_hooks,1202 base_url=base_url,1203 trust_env=trust_env,1204 )1205
189 unmodified lines
1395 await response.aread()1396 finally:1397 await response.aclose()13981399 try:1400 for hook in self._event_hooks["response"]:1401 await hook(response)1402 except Exception:1403 await response.aclose()1404 raise14051406 return response14071408 async def _send_handling_auth(1409 self,
5 unmodified lines
1415 ) -> Response:1416 auth_flow = auth.async_auth_flow(request)1417 request = await auth_flow.__anext__()14181419 for hook in self._event_hooks["request"]:1420 await hook(request)14211422 while True:1423 response = await self._send_handling_redirects(1424 request,1425 timeout=timeout,
399 unmodified lines
added:tests/client/test_event_hooks.py+189 added
1import pytest23import httpx4from tests.utils import AsyncMockTransport, MockTransport567def app(request: httpx.Request) -> httpx.Response:8 if request.url.path == "/redirect":9 return httpx.Response(303, headers={"server": "testserver", "location": "/"})10 elif request.url.path.startswith("/status/"):11 status_code = int(request.url.path[-3:])12 return httpx.Response(status_code, headers={"server": "testserver"})1314 return httpx.Response(200, headers={"server": "testserver"})151617def test_event_hooks():18 events = []1920 def on_request(request):21 events.append({"event": "request", "headers": dict(request.headers)})2223 def on_response(response):24 events.append({"event": "response", "headers": dict(response.headers)})2526 event_hooks = {"request": [on_request], "response": [on_response]}2728 with httpx.Client(event_hooks=event_hooks, transport=MockTransport(app)) as http:29 http.get("http://127.0.0.1:8000/", auth=("username", "password"))3031 assert events == [32 {33 "event": "request",34 "headers": {35 "host": "127.0.0.1:8000",36 "user-agent": f"python-httpx/{httpx.__version__}",37 "accept": "*/*",38 "accept-encoding": "gzip, deflate, br",39 "connection": "keep-alive",40 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",41 },42 },43 {44 "event": "response",45 "headers": {"server": "testserver"},46 },47 ]484950def test_event_hooks_raising_exception(server):51 def raise_on_4xx_5xx(response):52 response.raise_for_status()5354 event_hooks = {"response": [raise_on_4xx_5xx]}5556 with httpx.Client(event_hooks=event_hooks, transport=MockTransport(app)) as http:57 try:58 http.get("http://127.0.0.1:8000/status/400")59 except httpx.HTTPStatusError as exc:60 assert exc.response.is_closed616263@pytest.mark.usefixtures("async_environment")64async def test_async_event_hooks():65 events = []6667 async def on_request(request):68 events.append({"event": "request", "headers": dict(request.headers)})6970 async def on_response(response):71 events.append({"event": "response", "headers": dict(response.headers)})7273 event_hooks = {"request": [on_request], "response": [on_response]}7475 async with httpx.AsyncClient(76 event_hooks=event_hooks, transport=AsyncMockTransport(app)77 ) as http:78 await http.get("http://127.0.0.1:8000/", auth=("username", "password"))7980 assert events == [81 {82 "event": "request",83 "headers": {84 "host": "127.0.0.1:8000",85 "user-agent": f"python-httpx/{httpx.__version__}",86 "accept": "*/*",87 "accept-encoding": "gzip, deflate, br",88 "connection": "keep-alive",89 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",90 },91 },92 {93 "event": "response",94 "headers": {"server": "testserver"},95 },96 ]979899@pytest.mark.usefixtures("async_environment")100async def test_async_event_hooks_raising_exception():101 async def raise_on_4xx_5xx(response):102 response.raise_for_status()103104 event_hooks = {"response": [raise_on_4xx_5xx]}105106 async with httpx.AsyncClient(107 event_hooks=event_hooks, transport=AsyncMockTransport(app)108 ) as http:109 try:110 await http.get("http://127.0.0.1:8000/status/400")111 except httpx.HTTPStatusError as exc:112 assert exc.response.is_closed113114115def test_event_hooks_with_redirect():116 """117 A redirect request should not trigger a second 'request' event hook.118 """119120 events = []121122 def on_request(request):123 events.append({"event": "request", "headers": dict(request.headers)})124125 def on_response(response):126 events.append({"event": "response", "headers": dict(response.headers)})127128 event_hooks = {"request": [on_request], "response": [on_response]}129130 with httpx.Client(event_hooks=event_hooks, transport=MockTransport(app)) as http:131 http.get("http://127.0.0.1:8000/redirect", auth=("username", "password"))132133 assert events == [134 {135 "event": "request",136 "headers": {137 "host": "127.0.0.1:8000",138 "user-agent": f"python-httpx/{httpx.__version__}",139 "accept": "*/*",140 "accept-encoding": "gzip, deflate, br",141 "connection": "keep-alive",142 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",143 },144 },145 {146 "event": "response",147 "headers": {"server": "testserver"},148 },149 ]150151152@pytest.mark.usefixtures("async_environment")153async def test_async_event_hooks_with_redirect():154 """155 A redirect request should not trigger a second 'request' event hook.156 """157158 events = []159160 async def on_request(request):161 events.append({"event": "request", "headers": dict(request.headers)})162163 async def on_response(response):164 events.append({"event": "response", "headers": dict(response.headers)})165166 event_hooks = {"request": [on_request], "response": [on_response]}167168 async with httpx.AsyncClient(169 event_hooks=event_hooks, transport=AsyncMockTransport(app)170 ) as http:171 await http.get("http://127.0.0.1:8000/redirect", auth=("username", "password"))172173 assert events == [174 {175 "event": "request",176 "headers": {177 "host": "127.0.0.1:8000",178 "user-agent": f"python-httpx/{httpx.__version__}",179 "accept": "*/*",180 "accept-encoding": "gzip, deflate, br",181 "connection": "keep-alive",182 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",183 },184 },185 {186 "event": "response",187 "headers": {"server": "testserver"},188 },189 ]
modified:tests/client/test_properties.py+9 added
47 unmodified lines
48 assert client.timeout.connect == expected_timeout49 assert client.timeout.read == expected_timeout50 assert client.timeout.write == expected_timeout51 assert client.timeout.pool == expected_timeout525354def test_client_event_hooks():55 def on_request(request):56 pass # pragma: nocover5758 client = httpx.Client()59 client.event_hooks = {"request": [on_request]}60 assert client.event_hooks == {"request": [on_request], "response": []}