import asyncio
import aiohttp
urls = ['http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org']
async def call_url(url):
print('Starting {}'.format(url))
response = await aiohttp.ClientSession().get(url)
data = await response.text()
print('{}: {} bytes: {}'.format(url, len(data), data))
return data # ВОТ ПЕРЕМЕННАЯ
futures = [call_url(url) for url in urls]
ioloop = asyncio.get_event_loop()
ioloop.run_until_complete(asyncio.wait(futures))
print(data) # Тут хочу распечатать data
Don’t create a session per request. Most likely you need a session per application which performs all requests altogether.
import asyncio
import aiohttp
async def call_url(url, session):
print('Starting {}'.format(url))
async with session.get(url) as response:
response = await session.get(url)
data = await response.text()
print('{}: {} bytes: {}'.format(url, len(data), data))
return data
async def run(urls):
async with aiohttp.ClientSession() as session:
futures = [call_url(url, session) for url in urls]
result = await asyncio.gather(*futures)
return result
if __name__ == '__main__':
urls = ['http://www.google.com',
'http://www.yandex.ru', 'http://www.python.org']
ioloop = asyncio.get_event_loop()
data = ioloop.run_until_complete(run(urls))
print(data)
ioloop.close()