-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflags_asyncio.py
More file actions
60 lines (43 loc) · 1.37 KB
/
flags_asyncio.py
File metadata and controls
60 lines (43 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
import time
import sys
import asyncio # 1
import aiohttp # 2
POP20_CC = ('CN IN US ID BR PK NG BD RU JP '
'MX PH VN ET EG DE IR TR CD FR').split()
BASE_URL = 'http://flupy.org/data/flags'
DEST_DIR = 'downloads/'
def save_flag(img, filename):
path = os.path.join(DEST_DIR, filename)
with open(path, 'wb') as fp:
fp.write(img)
async def get_flag(session, cc): # 3
url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower())
async with session.get(url) as resp: # 4
return await resp.read() # 5
def show(text):
print(text, end=' ')
sys.stdout.flush()
async def download_one(session, cc): # 6
image = await get_flag(session, cc) # 7
show(cc)
save_flag(image, cc.lower() + '.gif')
return cc
async def download_many(cc_list):
async with aiohttp.ClientSession() as session: # 8
res = await asyncio.gather( # 9
*[asyncio.create_task(download_one(session, cc))\
for cc in sorted(cc_list)]
)
return len(res)
def main():
t0 = time.time()
# loop = asyncio.get_event_loop()
# count = loop.run_until_complete(download_many(POP20_CC))
# loop.close()
count = asyncio.run(download_many(POP20_CC))
elapsed = time.time() - t0
msg = '\n{} flags downloaded in {:.2f}s'
print(msg.format(count, elapsed))
if __name__ == '__main__':
main()