def countries(session): # We group by radio, mcc to take advantage of the index # and explicitly specify a small list of all valid radio values # to get mysql to actually use the index. radios = [v for v in RADIO_TYPE.values() if v >= 0] rows = session.query(Cell.radio, Cell.mcc, func.count()).filter( Cell.radio.in_(radios)).group_by(Cell.radio, Cell.mcc).all() # reverse grouping by mcc, radio codes = defaultdict(dict) for row in rows: codes[row[1]][row[0]] = row[2] countries = {} for code, item in codes.items(): names = [(c.name, c.alpha3) for c in mcc(str(code))] multiple = bool(len(names) > 1) for name, alpha3 in names: country = { 'code': alpha3, 'name': name, 'order': transliterate(name[:10].lower()), 'multiple': multiple, 'total': 0, 'gsm': 0, 'cdma': 0, 'umts': 0, 'lte': 0, } for t, v in item.items(): country[RADIO_TYPE_INVERSE[t]] = int(v) country['total'] = int(sum(item.values())) if alpha3 not in countries: countries[alpha3] = country else: # some countries like the US have multiple mcc codes, # we merge them here for k, v in country.items(): if isinstance(v, int): countries[alpha3][k] += v return sorted(countries.values(), key=itemgetter('name'))
def countries(session): # We group by radio, mcc to take advantage of the index # and explicitly specify a small list of all valid radio values # to get mysql to actually use the index. radios = [v for v in RADIO_TYPE.values() if v >= 0] rows = session.query(Cell.radio, Cell.mcc, func.count(Cell.id)).filter( Cell.radio.in_(radios)).group_by(Cell.radio, Cell.mcc).all() # reverse grouping by mcc, radio codes = defaultdict(dict) for row in rows: codes[row[1]][row[0]] = row[2] countries = {} for code, item in codes.items(): names = [(c.name, c.alpha3) for c in mcc(str(code))] multiple = bool(len(names) > 1) for name, alpha3 in names: country = { 'code': alpha3, 'name': name, 'order': transliterate(name[:10].lower()), 'multiple': multiple, 'total': 0, 'gsm': 0, 'cdma': 0, 'umts': 0, 'lte': 0, } for t, v in item.items(): country[RADIO_TYPE_INVERSE[t]] = int(v) country['total'] = int(sum(item.values())) if alpha3 not in countries: countries[alpha3] = country else: # some countries like the US have multiple mcc codes, # we merge them here for k, v in country.items(): if isinstance(v, int): countries[alpha3][k] += v return sorted(countries.values(), key=itemgetter('name'))