ch22: examples

This commit is contained in:
Luciano Ramalho
2021-02-28 21:19:40 -03:00
parent d2bcf655d7
commit a751c86836
10 changed files with 107 additions and 74 deletions

View File

@@ -20,31 +20,27 @@ from flags import BASE_URL, save_flag, main # <2>
async def download_one(session: ClientSession, cc: str): # <3>
image = await get_flag(session, cc)
save_flag(image, f'{cc}.gif')
print(cc, end=' ', flush=True)
save_flag(image, cc.lower() + '.gif')
return cc
async def get_flag(session: ClientSession, cc: str) -> bytes: # <4>
cc = cc.lower()
url = f'{BASE_URL}/{cc}/{cc}.gif'
url = f'{BASE_URL}/{cc}/{cc}.gif'.lower()
async with session.get(url) as resp: # <5>
print(resp)
return await resp.read() # <6>
# end::FLAGS_ASYNCIO_TOP[]
# end::FLAGS_ASYNCIO_START[]
def download_many(cc_list): # <1>
return asyncio.run(supervisor(cc_list)) # <2>
# tag::FLAGS_ASYNCIO_START[]
def download_many(cc_list: list[str]) -> int: # <1>
return asyncio.run(supervisor(cc_list)) # <2>
async def supervisor(cc_list):
async with ClientSession() as session: # <3>
to_do = [download_one(session, cc)
for cc in sorted(cc_list)] # <4>
res = await asyncio.gather(*to_do) # <5>
async def supervisor(cc_list: list[str]) -> int:
async with ClientSession() as session: # <3>
to_do = [download_one(session, cc) # <4>
for cc in sorted(cc_list)]
res = await asyncio.gather(*to_do) # <5>
return len(res) # <6>
return len(res) # <6>
if __name__ == '__main__':
main(download_many)