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
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
Provenance
- Commit
54f7708- Tree
f86adfd- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
d0fe113
4 files changed+294 added−0 removed
modified:docs/advanced.md+52 added
219 unmodified lines220 response = client.send(request)221 ...222 ```223 224+## Event Hooks225+226+HTTPX allows you to register "event hooks" with the client, that are called227+every time a particular type of event takes place.228+229+There are currently two event hooks:230+231+* `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.233+234+These allow you to install client-wide functionality such as logging and monitoring.235+236+```python237+def log_request(request):238+ print(f"Request event hook: {request.method} {request.url} - Waiting for response")239+240+def log_response(response):241+ request = response.request242+ print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")243+244+client = httpx.Client(event_hooks={'request': [log_request], 'response': [log_response]})245+```246+247+You can also use these hooks to install response processing code, such as this248+example, which creates a client instance that always raises `httpx.HTTPStatusError`249+on 4xx and 5xx responses.250+251+```python252+def raise_on_4xx_5xx(response):253+ response.raise_for_status()254+255+client = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]})256+```257+258+Event hooks must always be set as a **list of callables**, and you may register259+multiple event hooks for each type of event.260+261+As well as being able to set event hooks on instantiating the client, there262+is also an `.event_hooks` property, that allows you to inspect and modify263+the installed hooks.264+265+```python266+client = httpx.Client()267+client.event_hooks['request'] = [log_request]268+client.event_hooks['response'] = [log_response, raise_for_status]269+```270+271+!!! 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.275+276 ## Monitoring download progress277 278 If 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 linesmodified:httpx/_client.py+44 added
72 unmodified lines73 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_hooks82+83 self._base_url = self._enforce_trailing_slash(URL(base_url))84 85 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 lines140 def timeout(self, timeout: TimeoutTypes) -> None:141 self._timeout = Timeout(timeout)142 143 @property144+ def event_hooks(self) -> typing.Dict[str, typing.List[typing.Callable]]:145+ return self._event_hooks146+147+ @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+ }155+156+ @property157 def auth(self) -> typing.Optional[Auth]:158 """159 Authentication class used when none is passed at the request-level.160 390 unmodified lines551 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 lines564 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 lines760 response.read()761 finally:762 response.close()763 764+ try:765+ for hook in self._event_hooks["response"]:766+ hook(response)767+ except Exception:768+ response.close()769+ raise770+771 return response772 773 def _send_handling_auth(774 self,5 unmodified lines780 ) -> Response:781 auth_flow = auth.sync_auth_flow(request)782 request = next(auth_flow)783 784+ for hook in self._event_hooks["request"]:785+ hook(request)786+787 while True:788 response = self._send_handling_redirects(789 request,790 timeout=timeout,393 unmodified lines1184 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 lines1197 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 lines1395 await response.aread()1396 finally:1397 await response.aclose()1398 1399+ try:1400+ for hook in self._event_hooks["response"]:1401+ await hook(response)1402+ except Exception:1403+ await response.aclose()1404+ raise1405+1406 return response1407 1408 async def _send_handling_auth(1409 self,5 unmodified lines1415 ) -> Response:1416 auth_flow = auth.async_auth_flow(request)1417 request = await auth_flow.__anext__()1418 1419+ for hook in self._event_hooks["request"]:1420+ await hook(request)1421+1422 while True:1423 response = await self._send_handling_redirects(1424 request,1425 timeout=timeout,399 unmodified linesadded:tests/client/test_event_hooks.py+189 added
1+import pytest2+3+import httpx4+from tests.utils import AsyncMockTransport, MockTransport5+6+7+def 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"})13+14+ return httpx.Response(200, headers={"server": "testserver"})15+16+17+def test_event_hooks():18+ events = []19+20+ def on_request(request):21+ events.append({"event": "request", "headers": dict(request.headers)})22+23+ def on_response(response):24+ events.append({"event": "response", "headers": dict(response.headers)})25+26+ event_hooks = {"request": [on_request], "response": [on_response]}27+28+ with httpx.Client(event_hooks=event_hooks, transport=MockTransport(app)) as http:29+ http.get("http://127.0.0.1:8000/", auth=("username", "password"))30+31+ 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+ ]48+49+50+def test_event_hooks_raising_exception(server):51+ def raise_on_4xx_5xx(response):52+ response.raise_for_status()53+54+ event_hooks = {"response": [raise_on_4xx_5xx]}55+56+ 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_closed61+62+63+@pytest.mark.usefixtures("async_environment")64+async def test_async_event_hooks():65+ events = []66+67+ async def on_request(request):68+ events.append({"event": "request", "headers": dict(request.headers)})69+70+ async def on_response(response):71+ events.append({"event": "response", "headers": dict(response.headers)})72+73+ event_hooks = {"request": [on_request], "response": [on_response]}74+75+ 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"))79+80+ 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+ ]97+98+99+@pytest.mark.usefixtures("async_environment")100+async def test_async_event_hooks_raising_exception():101+ async def raise_on_4xx_5xx(response):102+ response.raise_for_status()103+104+ event_hooks = {"response": [raise_on_4xx_5xx]}105+106+ 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_closed113+114+115+def test_event_hooks_with_redirect():116+ """117+ A redirect request should not trigger a second 'request' event hook.118+ """119+120+ events = []121+122+ def on_request(request):123+ events.append({"event": "request", "headers": dict(request.headers)})124+125+ def on_response(response):126+ events.append({"event": "response", "headers": dict(response.headers)})127+128+ event_hooks = {"request": [on_request], "response": [on_response]}129+130+ 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"))132+133+ 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+ ]150+151+152+@pytest.mark.usefixtures("async_environment")153+async def test_async_event_hooks_with_redirect():154+ """155+ A redirect request should not trigger a second 'request' event hook.156+ """157+158+ events = []159+160+ async def on_request(request):161+ events.append({"event": "request", "headers": dict(request.headers)})162+163+ async def on_response(response):164+ events.append({"event": "response", "headers": dict(response.headers)})165+166+ event_hooks = {"request": [on_request], "response": [on_response]}167+168+ 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"))172+173+ 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 lines48 assert client.timeout.connect == expected_timeout49 assert client.timeout.read == expected_timeout50 assert client.timeout.write == expected_timeout51 assert client.timeout.pool == expected_timeout52+53+54+def test_client_event_hooks():55+ def on_request(request):56+ pass # pragma: nocover57+58+ client = httpx.Client()59+ client.event_hooks = {"request": [on_request]}60+ assert client.event_hooks == {"request": [on_request], "response": []}