Answer the question
In order to leave comments, you need to log in
How to get the data variable after executing an asynchronous function?
How to get the data variable and use it later in the program after the execution of the asynchronous function?
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
Answer the question
In order to leave comments, you need to log in
Sessions must be closed.
+
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()
In the call_url function, declare the date variable global
async def call_url(url):
global data
# print('Starting {}'.format(url))
response = await aiohttp.ClientSession().get(url)
data = await response.text()
# print('{}: {} bytes: {}'.format(url, len(data), data))
return data # ВОТ ПЕРЕМЕННАЯ
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question