Last active
March 22, 2018 09:11
-
-
Save dmiyakawa/6623fe3c1307064fbc6bc03e0ec1b1df to your computer and use it in GitHub Desktop.
asyncio example on "Fluent Python", modified
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# c.f. "Fluent Python" (Ja) p577 | |
# | |
import asyncio | |
import aiohttp | |
import sys | |
import time | |
POP20_CC = ['CN', 'IN', 'US', 'ID', 'BR', 'PK', 'NG', 'BD', 'RU', 'JP', | |
'MX', 'PH', 'VN', 'ET', 'EG', 'DE', 'IR', 'TR', 'CD', 'FR'] | |
BASE_URL = 'http://flupy.org/data/flags' | |
def show(text): | |
print(text, end=' ') | |
sys.stdout.flush() | |
async def get_flag(cc): | |
cc_lower = cc.lower() | |
url = f'{BASE_URL}/{cc_lower}/{cc_lower}.gif' | |
print(url) | |
async with aiohttp.ClientSession() as session: | |
async with session.get(url) as resp: | |
image = await resp.read() | |
return image | |
async def download_one(cc): | |
image = await get_flag(cc) | |
show(cc) | |
with open(f'/tmp/{cc}.gif', 'wb') as f: | |
f.write(image) | |
def download_many(cc_list): | |
loop = asyncio.get_event_loop() | |
to_do = [download_one(cc) for cc in sorted(cc_list)] | |
wait_coro = asyncio.wait(to_do) | |
res, _ = loop.run_until_complete(wait_coro) | |
loop.close() | |
return len(res) | |
def main(download_many): | |
t0 = time.time() | |
count = download_many(POP20_CC) | |
elapsed = time.time() - t0 | |
print(f'\n{count} flags downloaded in {elapsed:.2f}s') | |
if __name__ == '__main__': | |
main(download_many) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment