Instead of a static body, you can provide a callback function to register_uri. This allows you to modify the response dynamically based on the incoming request or internal logic.
Callback Signature
A callback must be a function with the following signature:
def callback(request, context):
...
Arguments
request: The requests.Request object used for the call.context: An object containing collected data about the response. You can modify the following properties on context to change the final response:context.status_code: The status code to return.context.reason: The HTTP status reason string.context.headers: A dictionary of headers to return.context.cookies: A requests_mock.CookieJar to be merged into the response.
The callback should return a value suitable for the body element type specified (e.g., a string if text was used, or a dict if json was used).
Note for raw responses: If you use a callback for the raw attribute, it must return an HTTPResponse. Ensure the HTTPResponse has preload_content=False to function correctly.
def text_callback(request, context):
context.status_code = 200
context.headers['Test1'] = 'value1'
return 'response'
adapter.register_uri('GET', 'mock://test.com/3', text=text_callback, headers={'Test2': 'value2'}, status_code=400)
# The resulting response will have status 200, headers {'Test1': 'value1', 'Test2': 'value2'}, and text 'response'