E
E
Eugene2018-10-16 22:20:40
Python
Eugene, 2018-10-16 22:20:40

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

4 answer(s)
I
igorzakhar, 2018-10-17
@ekam230

Sessions must be closed.
+

Don't create a session per request. Most likely you need a session per application which performs all requests altogether.

Sketched on the knee:
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()

S
Sergey Gornostaev, 2018-10-17
@sergey-gornostaev

results = await asyncio.gather(*futures)

A
Alexander, 2018-10-16
@sanya84

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 # ВОТ ПЕРЕМЕННАЯ

B
bbkmzzzz, 2018-10-16
@bbkmzzzz

With an asynchronous approach, the program logic is different. Here is a good read.
And don't use global variables.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question