final concurrency examples

This commit is contained in:
Luciano Ramalho
2015-03-13 18:24:31 -03:00
parent 39e87de5cd
commit 2d7a96742b
26 changed files with 1231 additions and 481 deletions

View File

@@ -5,58 +5,59 @@ Sequential version
Sample run::
$ python3 flags.py
BD retrieved.
BR retrieved.
CD retrieved.
...
TR retrieved.
US retrieved.
VN retrieved.
BD BR CD CN DE EG ET FR ID IN IR JP MX NG PH PK RU TR US VN
20 flags downloaded in 10.16s
"""
# BEGIN FLAGS_PY
import os
import time
import sys
import requests
import requests # <1>
POP20_CC = ('CN IN US ID BR PK NG BD RU JP '
'MX PH VN ET EG DE IR TR CD FR').split()
'MX PH VN ET EG DE IR TR CD FR').split() # <2>
BASE_URL = 'http://python.pro.br/fluent/data/flags'
BASE_URL = 'http://flupy.org/data/flags' # <3>
DEST_DIR = 'downloads/'
DEST_DIR = 'downloads/' # <4>
def save_flag(img, filename):
def save_flag(img, filename): # <5>
path = os.path.join(DEST_DIR, filename)
with open(path, 'wb') as fp:
fp.write(img)
def get_flag(cc):
def get_flag(cc): # <6>
url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower())
res = requests.get(url)
return res.content
resp = requests.get(url)
return resp.content
def download_many(cc_list):
for cc in sorted(cc_list):
def show(text): # <7>
print(text, end=' ')
sys.stdout.flush()
def download_many(cc_list): # <8>
for cc in sorted(cc_list): # <9>
image = get_flag(cc)
print('{} retrieved.'.format(cc))
show(cc)
save_flag(image, cc.lower() + '.gif')
return len(cc_list)
def main(download_many):
def main(download_many): # <10>
t0 = time.time()
count = download_many(POP20_CC)
elapsed = time.time() - t0
msg = '{} flags downloaded in {:.2f}s'
msg = '\n{} flags downloaded in {:.2f}s'
print(msg.format(count, elapsed))
if __name__ == '__main__':
main(download_many)
main(download_many) # <11>
# END FLAGS_PY