Python asynchronous requests with timer

Viewed 71

I'm trying to run a list of http get request to an url, following a trace of interarrival times between the requests (occasionally with concurrent requests at the same time). I'm currently using asyncio and aiohttp, anyway, I have to wait a lot more than the expected time (the one defined by the list of interarrival times) because it seems that the requests are still blocking the execution. My greatest issue is that I have also to try to get the response time for every request. Here's the snippet of code

async def main():
    iat = #list of seconds
    times = {}
    start_time = time.time()
    url = 'http://10.250.0.12:31112/function/weather-station'
    async with aiohttp.ClientSession() as session:
       for i in range(len(iat)):  ##iat == list of requests interarrival times
           s = iat[i] / 1000
           n = countlist[i]
           await asyncio.sleep(s)
           j = 1
           t0 = time.time()
           results[i] = []
           elapsed[i] = []
           while j <= n: ## n>1 if there are mutliple requests to be sent at the same time
               async with session.get(url) as response:
                   r = await response.json()
                   tr = time.time()
                   results[i].append(r['direction'])
                   times[i].append(tr - t0)
               j += 1
   end_time = time.time()
   print("exit, time:")
   print(end_time - start_time)

asyncio.run(main())

Is it possible to achieve this thing? Am I using the wrong methods? I'm using Python 3.7 on top of Windows 10.

0 Answers
Related