Switch event hooks to also run on redirects. (#1806)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Switch event hooks to also run on redirects * Bump coverage * Add pragma: no cover, because sometime ya just gotta be pragmatic * Update docs with note about response.read()
authored by Tom Christie · committed by GitHub · parent 4986743 · Browse files · 3 files·+52 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+52 added−16 removed
- tests:+32 added−2 removed
- other:+20 added−14 removed
Provenance
- Commit
2d9c358- Tree
3f4cc17- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
4986743
3 files changed+52 added−16 removed
modified:docs/advanced.md+8 added-1 removed
253 unmodified lines254 255 client = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]})256 ```257 258+!!! note259+ Response event hooks are called before determining if the response body260+ should be read or not.261+262+ If you need access to the response body inside an event hook, you'll263+ need to call `response.read()`.264+265 The hooks are also allowed to modify `request` and `response` objects.266 267 ```python268 def add_timestamp(request):269 request.headers['x-request-timestamp'] = datetime.now(tz=datetime.utc).isoformat()263- 270+271 client = httpx.Client(event_hooks={'request': [add_timestamp]})272 ```273 274 Event hooks must always be set as a **list of callables**, and you may register917 unmodified linesmodified:httpx/_client.py+12 added-13 removed
884 unmodified lines885 try:886 if not stream:887 response.read()888 889- for hook in self._event_hooks["response"]:890- hook(response)891-889 return response890 891 except Exception as exc:892 response.close()10 unmodified lines903 auth_flow = auth.sync_auth_flow(request)904 try:905 request = next(auth_flow)906 910- for hook in self._event_hooks["request"]:911- hook(request)912-907 while True:908 response = self._send_handling_redirects(909 request,910 timeout=timeout,29 unmodified lines940 raise TooManyRedirects(941 "Exceeded maximum allowed redirects.", request=request942 )943 944+ for hook in self._event_hooks["request"]:945+ hook(request)946+947 response = self._send_single_request(request, timeout)948 try:949+ for hook in self._event_hooks["response"]:950+ hook(response)951 response.history = list(history)952 953 if not response.is_redirect:954 return response638 unmodified lines1593 try:1594 if not stream:1595 await response.aread()1596 1598- for hook in self._event_hooks["response"]:1599- await hook(response)1600-1597 return response1598 1603- except Exception as exc:1599+ except Exception as exc: # pragma: no cover1600 await response.aclose()1601 raise exc1602 1603 async def _send_handling_auth(7 unmodified lines1611 auth_flow = auth.async_auth_flow(request)1612 try:1613 request = await auth_flow.__anext__()1614 1619- for hook in self._event_hooks["request"]:1620- await hook(request)1621-1615 while True:1616 response = await self._send_handling_redirects(1617 request,1618 timeout=timeout,29 unmodified lines1648 raise TooManyRedirects(1649 "Exceeded maximum allowed redirects.", request=request1650 )1651 1652+ for hook in self._event_hooks["request"]:1653+ await hook(request)1654+1655 response = await self._send_single_request(request, timeout)1656 try:1657+ for hook in self._event_hooks["response"]:1658+ await hook(response)1659+1660 response.history = list(history)1661 1662 if not response.is_redirect:1663 return response344 unmodified linesmodified:tests/client/test_event_hooks.py+32 added-2 removed
115 unmodified lines116 117 118 def test_event_hooks_with_redirect():119 """120- A redirect request should not trigger a second 'request' event hook.120+ A redirect request should trigger additional 'request' and 'response' event hooks.121 """122 123 events = []124 23 unmodified lines148 },149 },150 {151 "event": "response",152+ "headers": {"location": "/", "server": "testserver"},153+ },154+ {155+ "event": "request",156+ "headers": {157+ "host": "127.0.0.1:8000",158+ "user-agent": f"python-httpx/{httpx.__version__}",159+ "accept": "*/*",160+ "accept-encoding": "gzip, deflate, br",161+ "connection": "keep-alive",162+ "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",163+ },164+ },165+ {166+ "event": "response",167 "headers": {"server": "testserver"},168 },169 ]170 171 172 @pytest.mark.usefixtures("async_environment")173 async def test_async_event_hooks_with_redirect():174 """160- A redirect request should not trigger a second 'request' event hook.175+ A redirect request should trigger additional 'request' and 'response' event hooks.176 """177 178 events = []179 23 unmodified lines203 },204 },205 {206 "event": "response",207+ "headers": {"location": "/", "server": "testserver"},208+ },209+ {210+ "event": "request",211+ "headers": {212+ "host": "127.0.0.1:8000",213+ "user-agent": f"python-httpx/{httpx.__version__}",214+ "accept": "*/*",215+ "accept-encoding": "gzip, deflate, br",216+ "connection": "keep-alive",217+ "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",218+ },219+ },220+ {221+ "event": "response",222 "headers": {"server": "testserver"},223 },224 ]