|
| 1 | +"""Download flags of top 20 countries by population |
| 2 | +
|
| 3 | +asyncio + aiottp version |
| 4 | +
|
| 5 | +Sample run:: |
| 6 | +
|
| 7 | + $ python3 flags_asyncio.py |
| 8 | + CN EG BR IN ID RU NG VN JP DE TR PK FR ET MX PH US IR CD BD |
| 9 | + 20 flags downloaded in 0.35s |
| 10 | +
|
| 11 | +""" |
| 12 | +# BEGIN FLAGS_ASYNCIO |
| 13 | +import os |
| 14 | +import time |
| 15 | +import sys |
| 16 | +import asyncio # <1> |
| 17 | + |
| 18 | +import aiohttp # <2> |
| 19 | + |
| 20 | + |
| 21 | +POP20_CC = ('CN IN US ID BR PK NG BD RU JP ' |
| 22 | + 'MX PH VN ET EG DE IR TR CD FR').split() |
| 23 | + |
| 24 | +BASE_URL = 'http://flupy.org/data/flags' |
| 25 | + |
| 26 | +DEST_DIR = 'downloads/' |
| 27 | + |
| 28 | + |
| 29 | +def save_flag(img, filename): |
| 30 | + path = os.path.join(DEST_DIR, filename) |
| 31 | + with open(path, 'wb') as fp: |
| 32 | + fp.write(img) |
| 33 | + |
| 34 | + |
| 35 | +async def get_flag(session, cc): # <3> |
| 36 | + url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower()) |
| 37 | + async with session.get(url) as resp: # <4> |
| 38 | + return await resp.read() # <5> |
| 39 | + |
| 40 | + |
| 41 | +def show(text): |
| 42 | + print(text, end=' ') |
| 43 | + sys.stdout.flush() |
| 44 | + |
| 45 | + |
| 46 | +async def download_one(session, cc): # <6> |
| 47 | + image = await get_flag(session, cc) # <7> |
| 48 | + show(cc) |
| 49 | + save_flag(image, cc.lower() + '.gif') |
| 50 | + return cc |
| 51 | + |
| 52 | + |
| 53 | +async def download_many(cc_list): |
| 54 | + async with aiohttp.ClientSession() as session: # <8> |
| 55 | + res = await asyncio.gather( # <9> |
| 56 | + *[asyncio.create_task(download_one(session, cc)) |
| 57 | + for cc in sorted(cc_list)]) |
| 58 | + |
| 59 | + return len(res) |
| 60 | + |
| 61 | + |
| 62 | +def main(): # <10> |
| 63 | + t0 = time.time() |
| 64 | + count = asyncio.run(download_many(POP20_CC)) |
| 65 | + elapsed = time.time() - t0 |
| 66 | + msg = '\n{} flags downloaded in {:.2f}s' |
| 67 | + print(msg.format(count, elapsed)) |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == '__main__': |
| 71 | + main() |
| 72 | +# END FLAGS_ASYNCIO |
0 commit comments