How is this coroutine?

I am trying to understand coroutines in Python (and in general). I read about theory, concepts and a few examples, but I'm still struggling. I understand the asynchronous model (a few bits of Twisted), but not coroutines.

One tutorial gives this as an example of a coroutine (I made a few changes to illustrate my problem):

async def download_coroutine(url, number):
    """
    A coroutine to download the specified url
    """
    request = urllib.request.urlopen(url)
    filename = os.path.basename(url)
    print("Downloading %s" % url)

    with open(filename, 'wb') as file_handle:
        while True:
            print(number) # prints numbers to view progress
            chunk = request.read(1024)
            if not chunk:
                print("Finished")
                break
            file_handle.write(chunk)
    msg = 'Finished downloading {filename}'.format(filename=filename)
    return msg

This is done using this.

coroutines = [download_coroutine(url, number) for number, url in enumerate(urls)]
completed, pending = await asyncio.wait(coroutines)

Looking at examples of coroutines generators, I can see several operators yield. Nothing here, but urllib synchronously, AFAIK.

, , . (1, 4, 5, 1, 2,..., "",...). , , - , Finished, (3, 3, 3, 3,... "", 1, 1, 1, 1,..., ""...).

, , , .

+4
1

. ( ) , , . async Python 3.5 await - .

, , . Python, coroutine, , , async def.

, ... , , .

urllib HTTP-. aiohttp:

import aiohttp

async def download_coroutine(url):
    """
    A coroutine to download the specified url
    """
    filename = os.path.basename(url)
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            with open(filename, 'wb') as fd:
                while True:
                    chunk = await resp.content.read(1024)
                    if not chunk:
                        break
                    fd.write(chunk)
    msg = 'Finished downloading {filename}'.format(filename=filename)
    return msg

, .

, ; aiofiles project , . , , :

import aiofiles

async with aiofiles.open(filename, 'wb') as fd:
    while True:
        chunk = await resp.content.read(1024)
        if not chunk:
            break
        await fd.write(chunk)

. , .

+12

Source: https://habr.com/ru/post/1656364/


All Articles