fromtypingimportCallable,OptionalfromhttpximportRequest,ResponsefromwhistleimportEventfromharpimportget_loggerlogger=get_logger(__name__)#: Event fired when an external request is about to be sent by the HTTP client.EVENT_FILTER_HTTP_CLIENT_REQUEST="http_client.filter.request"#: Event fired when an external response is received by the HTTP client.EVENT_FILTER_HTTP_CLIENT_RESPONSE="http_client.filter.response"
[docs]classHttpClientFilterEvent(Event):""" Custom event class embedding an :class:`httpx.Request` and an optional :class:`httpx.Response`, allowing to filter external requests made by the client. It also allows script execution, providing some context for systems like filtering rules (see ``rules`` application). """
[docs]defset_response(self,response:Response):ifresponseisnotNoneandnotisinstance(response,Response):raiseValueError(f"Response must be an instance of httpx.Response, got {response!r} ({type(response).__module__}.{type(response).__qualname__}).")self.response=response
[docs]defexecute_script(self,script:Callable):context=self.create_execution_context()script(context)ifcontext["response"]!=self.response:ifcontext["response"]isnotNone:ifnotisinstance(context["response"],Response):raiseValueError(f"Response must be an instance of httpx.Response, got {context['response']!r} ({type(context['response']).__module__}.{type(context['response']).__qualname__}).")self.set_response(context["response"])returncontext