What's the recommended way of passing information to middlewares #2246
Description
Today we've come to a situation where we are not sure on how to solve it in a clean way using aiohttp, let me give some context:
For all endpoints we have, we want to send an event. This event is only sent depending on some values that come as an output from our view that uses json_response. We also want this event to contain some data generated in the view.
Since there is no field extras in the response object were we can store raw data so it can be used in the middlewares, we've thought of different approaches without any of them feeling "clean".
-
Send the event in each view explicitly (there is no middleware involved here) -> We haven't gone this way because it doesn't scale, imagine if we reach a point where we have lots of views and we change the data the event sends or how it is being sent.
-
Propagate the information through headers -> Super ugly, we are modifying our output to the clients just to be able to send an internal event.
-
Hack the response object once built to add a new field called
extrasor something like that so then we are able in the middleware to accessresponse.extrasand work from there.
Below is a pseudocode for our middleware:
async def apicall_handler(request):
response = await handler(request)
if some_response_value is True
send_metric_with_some_response_data()
return response
return apicall_handlerRight now we are going for number 3 but it still feels hacky.
So my question is, is there a clean way of doing this? If not, would it make sense to add an extras (or whatever name you prefer) in the Response object so users can propagate information to the middlewares?