|
| 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 | + CN EG BR IN ID RU NG VN JP DE TR PK FR ET MX PH US IR CD BD |
| 9 | + 20 flags downloaded in 0.35s |
| 10 | +
|
| 11 | +""" |
| 12 | +# BEGIN FLAGS_ASYNCIO |
| 13 | +importos |
| 14 | +importtime |
| 15 | +importsys |
| 16 | +importasyncio# <1> |
| 17 | + |
| 18 | +importaiohttp# <2> |
| 19 | + |
| 20 | + |
| 21 | +POP20_CC= ('CN IN US ID BR PK NG BD RU JP ' |
| 22 | +'MX PH VN ET EG DE IR TR CD FR').split() |
| 23 | + |
| 24 | +BASE_URL='http://flupy.org/data/flags' |
| 25 | + |
| 26 | +DEST_DIR='downloads/' |
| 27 | + |
| 28 | + |
| 29 | +defsave_flag(img,filename): |
| 30 | +path=os.path.join(DEST_DIR,filename) |
| 31 | +withopen(path,'wb')asfp: |
| 32 | +fp.write(img) |
| 33 | + |
| 34 | + |
| 35 | +asyncdefget_flag(session,cc):# <3> |
| 36 | +url='{}/{cc}/{cc}.gif'.format(BASE_URL,cc=cc.lower()) |
| 37 | +asyncwithsession.get(url)asresp:# <4> |
| 38 | +returnawaitresp.read()# <5> |
| 39 | + |
| 40 | + |
| 41 | +defshow(text): |
| 42 | +print(text,end=' ') |
| 43 | +sys.stdout.flush() |
| 44 | + |
| 45 | + |
| 46 | +asyncdefdownload_one(session,cc):# <6> |
| 47 | +image=awaitget_flag(session,cc)# <7> |
| 48 | +show(cc) |
| 49 | +save_flag(image,cc.lower()+'.gif') |
| 50 | +returncc |
| 51 | + |
| 52 | + |
| 53 | +asyncdefdownload_many(cc_list): |
| 54 | +asyncwithaiohttp.ClientSession()assession:# <8> |
| 55 | +res=awaitasyncio.gather(# <9> |
| 56 | +*[asyncio.create_task(download_one(session,cc)) |
| 57 | +forccinsorted(cc_list)]) |
| 58 | + |
| 59 | +returnlen(res) |
| 60 | + |
| 61 | + |
| 62 | +defmain():# <10> |
| 63 | +t0=time.time() |
| 64 | +count=asyncio.run(download_many(POP20_CC)) |
| 65 | +elapsed=time.time()-t0 |
| 66 | +msg='\n{} flags downloaded in {:.2f}s' |
| 67 | +print(msg.format(count,elapsed)) |
| 68 | + |
| 69 | + |
| 70 | +if__name__=='__main__': |
| 71 | +main() |
| 72 | +# END FLAGS_ASYNCIO |