I'm using aiohttp to perform some parallel HTTP post requests.
I have to set a timeout globally (on ClientSession) in order to not exceed a threshold.
The problem is that I would like to take the (partial in the sessions) responses that I have completed before the threshold, so for example if the session contains 10 requests and before the timeout I've completed 5 of these, I want to take the result of these 5. But I've not figured out how to do this.
The code I'm using is something like that:
import aiohttp
import asyncio
import requests
async def fetch(session):
async with session.get("https://amazon.com") as response:
return response.status
async def main(n, timeout):
async with aiohttp.ClientSession(timeout=timeout) as session:
return await asyncio.gather(*(fetch(session) for _ in range(n)))
timeout = aiohttp.ClientTimeout(total=0.4)
res = asyncio.run(main(10, timeout))
print(res)
With timeout = 0.4
it raises asyncio.TimeoutError
and I don't know how to get the partial performed responses.
For example, if I set the timeout at 5 seconds, all requests are completed and I obtain a list of ten 200
.
Thank you