Get Aiohttp Results As String
I'm trying to get data from a website using async in python. As an example I used this code (under A Better Coroutine Example): https://www.blog.pythonlibrary.org/2016/07/26/python
Solution 1:
The problem is in return tasks
at the end of main()
, which is not present in the original article. Instead of returning the coroutine objects (which are not useful once passed to asyncio.gather
), you should be returning the tuple returned by asyncio.gather
, which contains the results of running the coroutines in correct order. For example:
async def main(loop, urls):
async with aiohttp.ClientSession(loop=loop) as session:
tasks = [fetch(session, url) forurlin urls]
results = await asyncio.gather(*tasks)
return results
Now loop.run_until_complete(main(loop, urls))
will return a tuple of texts in the same order as the URLs.
Post a Comment for "Get Aiohttp Results As String"