Skip to content

Commit a16bd83

Browse files
committed
flags_await: start refactoring
1 parent e43f65c commit a16bd83

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

17-futures/countries/flags_await.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
EG VN IN TR RU ID US DE CN MX JP BD NG ET FR BR PH PK CD IR
9+
20 flags downloaded in 1.07s
10+
11+
"""
12+
# BEGIN FLAGS_ASYNCIO
13+
import asyncio
14+
15+
import aiohttp # <1>
16+
17+
from flags import BASE_URL, save_flag, show, main # <2>
18+
19+
20+
@asyncio.coroutine # <3>
21+
def get_flag(cc):
22+
url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower())
23+
resp = yield from aiohttp.request('GET', url) # <4>
24+
image = yield from resp.read() # <5>
25+
return image
26+
27+
28+
@asyncio.coroutine
29+
def download_one(cc): # <6>
30+
image = yield from get_flag(cc) # <7>
31+
show(cc)
32+
save_flag(image, cc.lower() + '.gif')
33+
return cc
34+
35+
36+
def download_many(cc_list):
37+
loop = asyncio.get_event_loop() # <8>
38+
to_do = [download_one(cc) for cc in sorted(cc_list)] # <9>
39+
wait_coro = asyncio.wait(to_do) # <10>
40+
res, _ = loop.run_until_complete(wait_coro) # <11>
41+
loop.close() # <12>
42+
43+
return len(res)
44+
45+
46+
if __name__ == '__main__':
47+
main(download_many)
48+
# END FLAGS_ASYNCIO

0 commit comments

Comments
 (0)