def user(id, rdb, mongodb): id = id.lower() user = mongodb.users_stats.find_one({'_id': id}) if not user: return abort(404) user['rank'] = {} langs = [lang for lang in user.get('contrib', {})] pipe = rdb.pipeline() if user.get('loc', {}).get('country') == 'China': for lang in langs: key = _format("country:{0}.lang:{1}:user".format(user.get('loc', {}).get('country', 'China'), lang)) pipe.zrevrank(key, id) user['rank']['China'] = {lang: rank + 1 for lang, rank in zip(langs, pipe.execute()) if rank is not None} user['loc_zh'] = {key: translate(text) for key, text in user.get('loc', {}).items() if key in ['country', 'state', 'city']} for lang in langs: key = _format("lang:{0}:user".format(lang)) pipe.zrevrank(key, id) user['rank']['World'] = {lang: rank + 1 for lang, rank in zip(langs, pipe.execute()) if rank is not None} return user
def _rank(lang, country, page, page_count, rdb, mongodb): key = _format("country:{0}.lang:{1}:user".format(country, lang)) total = rdb.zcard(key) pages = total/page_count + (total % page_count and 1) users = rdb.zrevrange(key, page*page_count, (page+1)*page_count - 1) w_key = _format("lang:{0}:user".format(lang)) pipe = rdb.pipeline() for u in users: pipe.zrevrank(w_key, u) w_ranks = pipe.execute() data = [mongodb.users_stats.find_one({'_id': u}, {'info': 1, 'contrib': 1}) for u in users] for i, (user, wr) in enumerate(zip(data, w_ranks)): user['rank'] = {country: page_count*page + i + 1, 'world': wr + 1} return { 'pages': pages, 'page': page, 'page_count': page_count, 'language': lang, 'country': country, 'data': data }