I would like to access the full request data including automatic headers and the url with query params without this hacky global variable. Headers may be passed either to the session or the request. I would like to be able to access this information in the case of any exception after the request object has been initialized (much like a requests.PreparedRequest object). Is there another modification to ClientRequest which would accomplish this?
I have tried a number of solutions which TraceConfig
which have not been successful. From this github issue, it seems that a CustomClientRequest
is the correct approach.
import aiohttp
import asyncio
class CustomRequest(aiohttp.ClientRequest):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
global request_data
request_data = {
"headers": self.headers,
"method": self.method,
"url": self.url,
"body": str(self.body),
}
async def main():
try:
async with aiohttp.ClientSession(request_class=CustomRequest) as client:
async with client.post(
"https://badlink.io", data="a=b", params={"x": "y"}, headers={"a": "b"}
) as resp:
await resp.text()
except Exception as e:
pass
print(request_data)
asyncio.run(main())