Uh oh!
There was an error while loading. Please reload this page.
Disabling event hooks per request #2991
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
This is somewhat similar to 2649, but not quite the same. My question is, is it possible to disable an event hook (or all) on a per-request basis? I think the specific use case that I have in mind is best illustrated with a code block: asyncdefrequest_hook(self, request):
ifself.tokenisNoneorself.token_has_expired():
self.token=awaitself.client.get("/token_endpoint")Obviously that creates an infinite recursion. Here's one method of disabling it for a single request: client.event_hooks= {"request": []}
self.token=awaitself.client.get("/token_endpoint")
client.event_hooks= {"request": [self.request_hook]} # Re-enabling it afterBut it seems prone to race conditions (and really doesn't look very nice). It would have been great if one could do, e.g. self.token=awaitself.client.get("/token_endpoint", event_hooks={"request": []})But that doesn't seem supported. Is there a recommended way of accomplishing this? |
Replies: 1 comment 1 reply
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hi! importhttpxasyncdefrequest_hook(self, request):
ifself.tokenisNoneorself.token_has_expired():
self.token=awaitself.client.get("/token_endpoint")
classCustomTransport(httpx.AsyncHTTPTransport):
asyncdefhandle_async_request(self, request: httpx.Request) ->httpx.Response:
ifnotrequest.extensions.get("disable_hooks", False):
awaitrequest_hook(request)
returnawaitsuper().handle_async_request(request)
client=httpx.AsyncClient(transport=CustomTransport())
awaitclient.get("/token_endpoint") # hook_worksawaitclient.get("/token_endpoint", extensions={"disable_hooks": True}) # hook doesn't work |
Hi!
I believe you can simply replace event hooks with custom transports as follows: