on_remote_response¶
The on_remote_response lifecycle event is triggered after the response is received from the remote server.
Please note that unlike on_response, this is not guaranteed to happen for every transaction (won’t happen for cached
or bypassed requests).
This allows to write logic that is specific for remote responses.
[rules."*"."*"]
on_remote_response = """
print(f'Hello, {response}.')
"""
rules:
"*":
"*":
on_remote_response: |
print(f'Hello, {response}.')
The event instance passed to on_remote_response lifecycle event scripts is a
HttpClientFilterEvent.
Note
The request and response (if set) variables are instances of httpx.Request and
httpx.Response.
Adding a response header¶
You can add a header to the incoming response:
[rules."*"."*"]
on_remote_response = """
response.headers['X-Goodbye'] = 'World'
"""
Overriding the Cache-Control¶
You can override the Cache-Control header of the incoming response to override the default caching behavior.
This will force revalidation on every use of a stored response (although you will prefer to set this on the request side):
[rules."*"."*"]
on_remote_response = """
response.headers['Cache-Control'] = 'no-cache'
"""
Or if you want to cache anonymous responses for one hour:
[rules."*"."GET *"]
on_remote_response = """
cache_control = response.headers.get('Cache-Control', '').lower()
if 'Authorization' not in request.headers and 'Cookie' not in request.headers and 'Set-Cookie' not in response.headers and 'private' not in cache_control:
response.headers['Cache-Control'] = 'max-age=3600'
"""
Warning
The HTTP cache is shared: a response stored for one caller is served to the next. Only force caching on
requests that carry no identity, and never override private. See the
shared cache warning.
Switching the response¶
Although the reason may be debatable, if you need to, you can replace the response entirely:
[rules."*"."*"]
on_remote_response = """
from httpx import Response
response = Response(200, content=b'Goodbye, World!')
"""
Context reference¶
The following variables are available in the context of the on_remote_response lifecycle event:
logger: the logger instance.rule: the rule name for this transaction, as defined in your configuration.request: thehttpx.Requestinstance.response: thehttpx.Responseinstance. You can amend or replace it.stop_propagation: a function to stop the event propagation to the next lifecycle event.
Warning
Don’t use stop_propagation for now, as it will stop the whole lifecycle processing
(whistle#18).