Sep-21-2020, 06:38 PM
1.) yes good point, you definitely don't want to create a session per request, so in this case you can just move the context manager in the
gather_coro
and pass it as a argument to get_url_result
function:def get_results(urls): async def gather_coro(): async with aiohttp.ClientSession() as session: # moved here from get_url_result return await asyncio.gather(*(get_url_result(url, session) for url in urls)) url_results = asyncio.run(gather_coro()) return dict(url_results)2.) Yes,
get_url_result
can return just resp
, creation of dictionary really shouldn't be a problem! But remember that in order to access response content like resp.text()
you need to await it, this means you won't be able to access it from a normal function but only from coroutine, from docs - Quote:aiohttp loads only the headers when .get() is executed, letting you decide to pay the cost of loading the body afterward, in a second asynchronous operation. Hence the await response.text().