2_chaining_with_await.py 947 Bytes
#!/usr/bin/env python
import asyncio
import aiohttp

async def get_page(url):
    try:
        print("get {}".format(url))
        response = await aiohttp.get(url)
        print("got {}".format(url))
        return await response.text()

    except aiohttp.errors.ClientError as e:
        print("error getting {}: {}".format(url, e))
        return ""


async def text_length(url):
    text = await get_page(url)
    return len(text)


async def text_lengths(urls):
    lengths = await asyncio.gather(*[
        text_length(url) for url in urls
        ])
    for u, l in zip(urls, lengths):
        print("{}: {} bytes text".format(u, l))


urls = [
        "https://www.uit.no",
        "https://www.uio.no",
        "https://www.uib.no",
        "https://www.ntnu.no",
        "http://utviklerlunsj.uit.no",
        "https://www.ihopethisdoesntexist.no/",
        ]
loop = asyncio.get_event_loop()
loop.run_until_complete(text_lengths(urls))