|
| 1 | +"""Utilities for second set of flag examples. |
| 2 | +""" |
| 3 | + |
| 4 | +import os |
| 5 | +import time |
| 6 | +import sys |
| 7 | +import string |
| 8 | +import argparse |
| 9 | +from collections import namedtuple, Counter |
| 10 | +from enum import Enum |
| 11 | + |
| 12 | + |
| 13 | +Result = namedtuple('Result', 'status data') |
| 14 | + |
| 15 | +HTTPStatus = Enum('HTTPStatus', 'ok not_found error') |
| 16 | + |
| 17 | +POP20_CC = ('CN IN US ID BR PK NG BD RU JP ' |
| 18 | + 'MX PH VN ET EG DE IR TR CD FR').split() |
| 19 | + |
| 20 | +DEFAULT_CONCUR_REQ = 1 |
| 21 | +MAX_CONCUR_REQ = 1 |
| 22 | + |
| 23 | +SERVERS = { |
| 24 | + 'REMOTE': 'http://fluentpython.com/data/flags', |
| 25 | + 'LOCAL': 'http://localhost:8000/flags', |
| 26 | + 'DELAY': 'http://localhost:8001/flags', |
| 27 | + 'ERROR': 'http://localhost:8002/flags', |
| 28 | +} |
| 29 | +DEFAULT_SERVER = 'LOCAL' |
| 30 | + |
| 31 | +DEST_DIR = 'downloaded/' |
| 32 | +COUNTRY_CODES_FILE = 'country_codes.txt' |
| 33 | + |
| 34 | + |
| 35 | +def save_flag(img: bytes, filename: str) -> None: |
| 36 | + path = os.path.join(DEST_DIR, filename) |
| 37 | + with open(path, 'wb') as fp: |
| 38 | + fp.write(img) |
| 39 | + |
| 40 | + |
| 41 | +def initial_report(cc_list: list[str], |
| 42 | + actual_req: int, |
| 43 | + server_label: str) -> None: |
| 44 | + if len(cc_list) <= 10: |
| 45 | + cc_msg = ', '.join(cc_list) |
| 46 | + else: |
| 47 | + cc_msg = 'from {} to {}'.format(cc_list[0], cc_list[-1]) |
| 48 | + print('{} site: {}'.format(server_label, SERVERS[server_label])) |
| 49 | + msg = 'Searching for {} flag{}: {}' |
| 50 | + plural = 's' if len(cc_list) != 1 else '' |
| 51 | + print(msg.format(len(cc_list), plural, cc_msg)) |
| 52 | + plural = 's' if actual_req != 1 else '' |
| 53 | + msg = '{} concurrent connection{} will be used.' |
| 54 | + print(msg.format(actual_req, plural)) |
| 55 | + |
| 56 | + |
| 57 | +def final_report(cc_list: list[str], |
| 58 | + counter: Counter[HTTPStatus], |
| 59 | + start_time: float) -> None: |
| 60 | + elapsed = time.time() - start_time |
| 61 | + print('-' * 20) |
| 62 | + msg = '{} flag{} downloaded.' |
| 63 | + plural = 's' if counter[HTTPStatus.ok] != 1 else '' |
| 64 | + print(msg.format(counter[HTTPStatus.ok], plural)) |
| 65 | + if counter[HTTPStatus.not_found]: |
| 66 | + print(counter[HTTPStatus.not_found], 'not found.') |
| 67 | + if counter[HTTPStatus.error]: |
| 68 | + plural = 's' if counter[HTTPStatus.error] != 1 else '' |
| 69 | + print('{} error{}.'.format(counter[HTTPStatus.error], plural)) |
| 70 | + print('Elapsed time: {:.2f}s'.format(elapsed)) |
| 71 | + |
| 72 | + |
| 73 | +def expand_cc_args(every_cc: bool, |
| 74 | + all_cc: bool, |
| 75 | + cc_args: list[str], |
| 76 | + limit: int) -> list[str]: |
| 77 | + codes: set[str] = set() |
| 78 | + A_Z = string.ascii_uppercase |
| 79 | + if every_cc: |
| 80 | + codes.update(a+b for a in A_Z for b in A_Z) |
| 81 | + elif all_cc: |
| 82 | + with open(COUNTRY_CODES_FILE) as fp: |
| 83 | + text = fp.read() |
| 84 | + codes.update(text.split()) |
| 85 | + else: |
| 86 | + for cc in (c.upper() for c in cc_args): |
| 87 | + if len(cc) == 1 and cc in A_Z: |
| 88 | + codes.update(cc+c for c in A_Z) |
| 89 | + elif len(cc) == 2 and all(c in A_Z for c in cc): |
| 90 | + codes.add(cc) |
| 91 | + else: |
| 92 | + msg = 'each CC argument must be A to Z or AA to ZZ.' |
| 93 | + raise ValueError('*** Usage error: '+msg) |
| 94 | + return sorted(codes)[:limit] |
| 95 | + |
| 96 | + |
| 97 | +def process_args(default_concur_req): |
| 98 | + server_options = ', '.join(sorted(SERVERS)) |
| 99 | + parser = argparse.ArgumentParser( |
| 100 | + description='Download flags for country codes. ' |
| 101 | + 'Default: top 20 countries by population.') |
| 102 | + parser.add_argument('cc', metavar='CC', nargs='*', |
| 103 | + help='country code or 1st letter (eg. B for BA...BZ)') |
| 104 | + parser.add_argument('-a', '--all', action='store_true', |
| 105 | + help='get all available flags (AD to ZW)') |
| 106 | + parser.add_argument('-e', '--every', action='store_true', |
| 107 | + help='get flags for every possible code (AA...ZZ)') |
| 108 | + parser.add_argument('-l', '--limit', metavar='N', type=int, |
| 109 | + help='limit to N first codes', default=sys.maxsize) |
| 110 | + parser.add_argument('-m', '--max_req', metavar='CONCURRENT', type=int, |
| 111 | + default=default_concur_req, |
| 112 | + help=f'maximum concurrent requests (default={default_concur_req})') |
| 113 | + parser.add_argument('-s', '--server', metavar='LABEL', |
| 114 | + default=DEFAULT_SERVER, |
| 115 | + help=('Server to hit; one of ' + |
| 116 | + f'{server_options} (default={DEFAULT_SERVER})')) |
| 117 | + parser.add_argument('-v', '--verbose', action='store_true', |
| 118 | + help='output detailed progress info') |
| 119 | + args = parser.parse_args() |
| 120 | + if args.max_req < 1: |
| 121 | + print('*** Usage error: --max_req CONCURRENT must be >= 1') |
| 122 | + parser.print_usage() |
| 123 | + sys.exit(1) |
| 124 | + if args.limit < 1: |
| 125 | + print('*** Usage error: --limit N must be >= 1') |
| 126 | + parser.print_usage() |
| 127 | + sys.exit(1) |
| 128 | + args.server = args.server.upper() |
| 129 | + if args.server not in SERVERS: |
| 130 | + print('*** Usage error: --server LABEL must be one of', |
| 131 | + server_options) |
| 132 | + parser.print_usage() |
| 133 | + sys.exit(1) |
| 134 | + try: |
| 135 | + cc_list = expand_cc_args(args.every, args.all, args.cc, args.limit) |
| 136 | + except ValueError as exc: |
| 137 | + print(exc.args[0]) |
| 138 | + parser.print_usage() |
| 139 | + sys.exit(1) |
| 140 | + |
| 141 | + if not cc_list: |
| 142 | + cc_list = sorted(POP20_CC) |
| 143 | + return args, cc_list |
| 144 | + |
| 145 | + |
| 146 | +def main(download_many, default_concur_req, max_concur_req): |
| 147 | + args, cc_list = process_args(default_concur_req) |
| 148 | + actual_req = min(args.max_req, max_concur_req, len(cc_list)) |
| 149 | + initial_report(cc_list, actual_req, args.server) |
| 150 | + base_url = SERVERS[args.server] |
| 151 | + t0 = time.time() |
| 152 | + counter = download_many(cc_list, base_url, args.verbose, actual_req) |
| 153 | + assert sum(counter.values()) == len(cc_list), \ |
| 154 | + 'some downloads are unaccounted for' |
| 155 | + final_report(cc_list, counter, t0) |
0 commit comments