1818# BEGIN FLAGS2_ASYNCIO_TOP
1919import asyncio
2020import collections
21+ from contextlib import closing
2122
2223import aiohttp
2324from aiohttp import web
@@ -36,26 +37,24 @@ def __init__(self, country_code):
3637 self .country_code = country_code
3738
3839
39- @asyncio .coroutine
40- def get_flag (base_url , cc ): # <2>
40+ async def get_flag (base_url , cc ): # <2>
4141 url = '{}/{cc}/{cc}.gif' .format (base_url , cc = cc .lower ())
42- resp = yield from aiohttp .request ('GET' , url )
43- if resp .status == 200 :
44- image = yield from resp .read ()
45- return image
46- elif resp .status == 404 :
47- raise web .HTTPNotFound ()
48- else :
49- raise aiohttp .HttpProcessingError (
50- code = resp .status , message = resp .reason ,
51- headers = resp .headers )
42+ with closing ( await aiohttp .request ('GET' , url )) as resp :
43+ if resp .status == 200 :
44+ image = await resp .read ()
45+ return image
46+ elif resp .status == 404 :
47+ raise web .HTTPNotFound ()
48+ else :
49+ raise aiohttp .HttpProcessingError (
50+ code = resp .status , message = resp .reason ,
51+ headers = resp .headers )
5252
5353
54- @asyncio .coroutine
55- def download_one (cc , base_url , semaphore , verbose ): # <3>
54+ async def download_one (cc , base_url , semaphore , verbose ): # <3>
5655 try :
57- with (yield from semaphore ): # <4>
58- image = yield from get_flag (base_url , cc ) # <5>
56+ with (await semaphore ): # <4>
57+ image = await get_flag (base_url , cc ) # <5>
5958 except web .HTTPNotFound : # <6>
6059 status = HTTPStatus .not_found
6160 msg = 'not found'
@@ -73,8 +72,7 @@ def download_one(cc, base_url, semaphore, verbose): # <3>
7372# END FLAGS2_ASYNCIO_TOP
7473
7574# BEGIN FLAGS2_ASYNCIO_DOWNLOAD_MANY
76- @asyncio .coroutine
77- def downloader_coro (cc_list , base_url , verbose , concur_req ): # <1>
75+ async def downloader_coro (cc_list , base_url , verbose , concur_req ): # <1>
7876 counter = collections .Counter ()
7977 semaphore = asyncio .Semaphore (concur_req ) # <2>
8078 to_do = [download_one (cc , base_url , semaphore , verbose )
@@ -85,7 +83,7 @@ def downloader_coro(cc_list, base_url, verbose, concur_req): # <1>
8583 to_do_iter = tqdm .tqdm (to_do_iter , total = len (cc_list )) # <5>
8684 for future in to_do_iter : # <6>
8785 try :
88- res = yield from future # <7>
86+ res = await future # <7>
8987 except FetchError as exc : # <8>
9088 country_code = exc .country_code # <9>
9189 try :
0 commit comments