From 349dd5c4cdd51b406f58f817291e8f98e1da60a3 Mon Sep 17 00:00:00 2001
From: nyov <nyov@nexnode.net>
Date: Thu, 17 May 2012 00:55:51 +0200
Subject: [PATCH] refactored views in preparation for json output

---
 xonstat/__init__.py       |  2 +-
 xonstat/views/__init__.py |  4 +--
 xonstat/views/game.py     | 32 ++++++++++++------
 xonstat/views/main.py     | 69 +++++++++++++++++++++++----------------
 xonstat/views/map.py      | 52 ++++++++++++++++-------------
 xonstat/views/player.py   | 62 ++++++++++++++++++++++-------------
 xonstat/views/search.py   |  6 +++-
 xonstat/views/server.py   | 64 +++++++++++++++++++++++-------------
 8 files changed, 180 insertions(+), 111 deletions(-)

diff --git a/xonstat/__init__.py b/xonstat/__init__.py
index d3a6d98..5a164ef 100755
--- a/xonstat/__init__.py
+++ b/xonstat/__init__.py
@@ -42,7 +42,7 @@ def main(global_config, **settings):
         renderer="player_info.mako")
 
     config.add_route("player_accuracy", "/player/{id:\d+}/accuracy")
-    config.add_view(player_accuracy, route_name="player_accuracy",
+    config.add_view(player_accuracy_json, route_name="player_accuracy",
         renderer="json")
 
     # GAME ROUTES
diff --git a/xonstat/views/__init__.py b/xonstat/views/__init__.py
index 5592f2c..7f1de44 100755
--- a/xonstat/views/__init__.py
+++ b/xonstat/views/__init__.py
@@ -1,8 +1,8 @@
 from xonstat.views.submission import stats_submit
 from xonstat.views.player import player_index, player_info, player_game_index
-from xonstat.views.player import player_accuracy
+from xonstat.views.player import player_accuracy_json
 from xonstat.views.game import game_index, game_info, rank_index
 from xonstat.views.map import map_info, map_index, map_index_json
 from xonstat.views.server import server_info, server_game_index, server_index
-from xonstat.views.search import *
+from xonstat.views.search import search_q, search
 from xonstat.views.main import main_index
diff --git a/xonstat/views/game.py b/xonstat/views/game.py
index 336acba..44e929e 100755
--- a/xonstat/views/game.py
+++ b/xonstat/views/game.py
@@ -11,12 +11,7 @@ from xonstat.util import page_url
 log = logging.getLogger(__name__)
 
 
-def game_index(request):
-    """
-    Provides a list of current games, with the associated game stats.
-    These games are ordered by game_id, with the most current ones first.
-    Paginated.
-    """
+def _game_index_data(request):
     if request.params.has_key('page'):
         current_page = request.params['page']
     else:
@@ -40,10 +35,16 @@ def game_index(request):
             'pgstats':pgstats}
 
 
-def game_info(request):
+def game_index(request):
     """
-    List the game stats (scoreboard) for a particular game. Paginated.
+    Provides a list of current games, with the associated game stats.
+    These games are ordered by game_id, with the most current ones first.
+    Paginated.
     """
+    return _game_index_data(request)
+
+
+def _game_info_data(request):
     game_id = request.matchdict['id']
     try:
         notfound = False
@@ -95,10 +96,14 @@ def game_info(request):
             }
 
 
-def rank_index(request):
+def game_info(request):
     """
-    Provide a list of gametype ranks, paginated.
+    List the game stats (scoreboard) for a particular game. Paginated.
     """
+    return _game_info_data(request)
+
+
+def _rank_index_data(request):
     if request.params.has_key('page'):
         current_page = request.params['page']
     else:
@@ -119,3 +124,10 @@ def rank_index(request):
             'ranks':ranks,
             'game_type_cd':game_type_cd,
            }
+
+
+def rank_index(request):
+    """
+    Provide a list of gametype ranks, paginated.
+    """
+    return _rank_index_data(request)
diff --git a/xonstat/views/main.py b/xonstat/views/main.py
index 51624d5..5a8bad4 100755
--- a/xonstat/views/main.py
+++ b/xonstat/views/main.py
@@ -8,7 +8,7 @@ from xonstat.util import *
 
 log = logging.getLogger(__name__)
 
-def main_index(request):
+def _main_index_data(request):
     try: 
         leaderboard_lifetime = int(
                 request.registry.settings['xonstat.leaderboard_lifetime'])
@@ -23,40 +23,31 @@ def main_index(request):
             PlayerRank.elo).\
             filter(PlayerRank.game_type_cd=='duel').\
             order_by(PlayerRank.rank).\
-            limit(10).all()
+            limit(leaderboard_count).all()
 
     duel_ranks = [(player_id, html_colors(nick), elo) \
             for (player_id, nick, elo) in duel_ranks]
 
-    for i in range(leaderboard_count-len(duel_ranks)):
-        duel_ranks.append(('-', '-', '-'))
-
     # top ranked CTF-ers
     ctf_ranks = DBSession.query(PlayerRank.player_id, PlayerRank.nick, 
             PlayerRank.elo).\
             filter(PlayerRank.game_type_cd=='ctf').\
             order_by(PlayerRank.rank).\
-            limit(10).all()
+            limit(leaderboard_count).all()
 
     ctf_ranks = [(player_id, html_colors(nick), elo) \
             for (player_id, nick, elo) in ctf_ranks]
 
-    for i in range(leaderboard_count-len(ctf_ranks)):
-        ctf_ranks.append(('-', '-', '-'))
-
     # top ranked DM-ers
     dm_ranks = DBSession.query(PlayerRank.player_id, PlayerRank.nick, 
             PlayerRank.elo).\
             filter(PlayerRank.game_type_cd=='dm').\
             order_by(PlayerRank.rank).\
-            limit(10).all()
+            limit(leaderboard_count).all()
 
     dm_ranks = [(player_id, html_colors(nick), elo) \
             for (player_id, nick, elo) in dm_ranks]
 
-    for i in range(leaderboard_count-len(dm_ranks)):
-        dm_ranks.append(('-', '-', '-'))
-
     right_now = datetime.utcnow()
     back_then = datetime.utcnow() - timedelta(days=leaderboard_lifetime)
 
@@ -68,14 +59,11 @@ def main_index(request):
             filter(expr.between(PlayerGameStat.create_dt, back_then, right_now)).\
             order_by(expr.desc(func.sum(PlayerGameStat.alivetime))).\
             group_by(Player.nick).\
-            group_by(Player.player_id).limit(10).all()
+            group_by(Player.player_id).limit(leaderboard_count).all()
 
     top_players = [(player_id, html_colors(nick), score) \
             for (player_id, nick, score) in top_players]
 
-    for i in range(leaderboard_count-len(top_players)):
-        top_players.append(('-', '-', '-'))
-
     # top servers by number of total players played
     top_servers = DBSession.query(Server.server_id, Server.name, 
             func.count()).\
@@ -83,10 +71,7 @@ def main_index(request):
             filter(expr.between(Game.create_dt, back_then, right_now)).\
             order_by(expr.desc(func.count(Game.game_id))).\
             group_by(Server.server_id).\
-            group_by(Server.name).limit(10).all()
-
-    for i in range(leaderboard_count-len(top_servers)):
-        top_servers.append(('-', '-', '-'))
+            group_by(Server.name).limit(leaderboard_count).all()
 
     # top maps by total times played
     top_maps = DBSession.query(Game.map_id, Map.name, 
@@ -95,10 +80,7 @@ def main_index(request):
             filter(expr.between(Game.create_dt, back_then, right_now)).\
             order_by(expr.desc(func.count())).\
             group_by(Game.map_id).\
-            group_by(Map.name).limit(10).all()
-
-    for i in range(leaderboard_count-len(top_maps)):
-        top_maps.append(('-', '-', '-'))
+            group_by(Map.name).limit(leaderboard_count).all()
 
     # recent games played in descending order
     recent_games = DBSession.query(Game, Server, Map, PlayerGameStat).\
@@ -109,9 +91,6 @@ def main_index(request):
             filter(expr.between(Game.create_dt, back_then, right_now)).\
             order_by(expr.desc(Game.start_dt)).limit(recent_games_count).all()
 
-    for i in range(recent_games_count-len(recent_games)):
-        recent_games.append(('-', '-', '-', '-'))
-
     return {'top_players':top_players,
             'top_servers':top_servers,
             'top_maps':top_maps,
@@ -120,3 +99,37 @@ def main_index(request):
             'ctf_ranks':ctf_ranks,
             'dm_ranks':dm_ranks,
             }
+
+
+def main_index(request):
+    """
+    Display the main page information.
+    """
+    mainindex_data =  _main_index_data(request)
+
+    # FIXME: code clone, should get these from _main_index_data
+    leaderboard_count = 10
+    recent_games_count = 20
+
+    for i in range(leaderboard_count-len(mainindex_data['duel_ranks'])):
+        mainindex_data['duel_ranks'].append(('-', '-', '-'))
+
+    for i in range(leaderboard_count-len(mainindex_data['ctf_ranks'])):
+        mainindex_data['ctf_ranks'].append(('-', '-', '-'))
+
+    for i in range(leaderboard_count-len(mainindex_data['dm_ranks'])):
+        mainindex_data['dm_ranks'].append(('-', '-', '-'))
+
+    for i in range(leaderboard_count-len(mainindex_data['top_players'])):
+        mainindex_data['top_players'].append(('-', '-', '-'))
+
+    for i in range(leaderboard_count-len(mainindex_data['top_servers'])):
+        mainindex_data['top_servers'].append(('-', '-', '-'))
+
+    for i in range(leaderboard_count-len(mainindex_data['top_maps'])):
+        mainindex_data['top_maps'].append(('-', '-', '-'))
+
+    for i in range(recent_games_count-len(mainindex_data['recent_games'])):
+        mainindex_data['recent_games'].append(('-', '-', '-', '-'))
+
+    return mainindex_data
diff --git a/xonstat/views/map.py b/xonstat/views/map.py
index 6b947eb..86e70ad 100755
--- a/xonstat/views/map.py
+++ b/xonstat/views/map.py
@@ -11,9 +11,6 @@ from xonstat.util import page_url
 log = logging.getLogger(__name__)
 
 def _map_index_data(request):
-    """
-    Provides a list of all the current maps. 
-    """
     if request.params.has_key('page'):
         current_page = request.params['page']
     else:
@@ -49,10 +46,7 @@ def map_index_json(request):
     return maps
 
 
-def map_info(request):
-    """
-    List the information stored about a given map. 
-    """
+def _map_info_data(request):
     map_id = request.matchdict['id']
 
     try: 
@@ -76,10 +70,6 @@ def map_info(request):
             filter(PlayerGameStat.rank==1).\
             order_by(expr.desc(Game.start_dt)).all()[0:recent_games_count]
 
-        for i in range(recent_games_count-len(recent_games)):
-            recent_games.append(('-', '-', '-', '-'))
-
-
         # top players by score
         top_scorers = DBSession.query(Player.player_id, Player.nick,
                 func.sum(PlayerGameStat.score)).\
@@ -91,14 +81,11 @@ def map_info(request):
                         (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
                 order_by(expr.desc(func.sum(PlayerGameStat.score))).\
                 group_by(Player.nick).\
-                group_by(Player.player_id).all()[0:10]
+                group_by(Player.player_id).all()[0:leaderboard_count]
 
         top_scorers = [(player_id, html_colors(nick), score) \
                 for (player_id, nick, score) in top_scorers]
 
-        for i in range(leaderboard_count-len(top_scorers)):
-            top_scorers.append(('-', '-', '-'))
-
         # top players by playing time
         top_players = DBSession.query(Player.player_id, Player.nick, 
                 func.sum(PlayerGameStat.alivetime)).\
@@ -110,14 +97,11 @@ def map_info(request):
                         (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
                 order_by(expr.desc(func.sum(PlayerGameStat.alivetime))).\
                 group_by(Player.nick).\
-                group_by(Player.player_id).all()[0:10]
+                group_by(Player.player_id).all()[0:leaderboard_count]
 
         top_players = [(player_id, html_colors(nick), score) \
                 for (player_id, nick, score) in top_players]
 
-        for i in range(leaderboard_count-len(top_players)):
-            top_players.append(('-', '-', '-'))
-
         # top servers using/playing this map
         top_servers = DBSession.query(Server.server_id, Server.name, 
                 func.count(Game.game_id)).\
@@ -127,10 +111,7 @@ def map_info(request):
                         (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
                 order_by(expr.desc(func.count(Game.game_id))).\
                 group_by(Server.name).\
-                group_by(Server.server_id).all()[0:10]
-
-        for i in range(leaderboard_count-len(top_servers)):
-            top_servers.append(('-', '-', '-'))
+                group_by(Server.server_id).all()[0:leaderboard_count]
 
     except Exception as e:
         gmap = None
@@ -140,3 +121,28 @@ def map_info(request):
             'top_players':top_players,
             'top_servers':top_servers,
             }
+
+
+def map_info(request):
+    """
+    List the information stored about a given map.
+    """
+    mapinfo_data =  _map_info_data(request)
+
+    # FIXME: code clone, should get these from _map_info_data
+    leaderboard_count = 10
+    recent_games_count = 20
+
+    for i in range(recent_games_count-len(mapinfo_data['recent_games'])):
+        mapinfo_data['recent_games'].append(('-', '-', '-', '-'))
+
+    for i in range(leaderboard_count-len(mapinfo_data['top_scorers'])):
+        mapinfo_data['top_scorers'].append(('-', '-', '-'))
+
+    for i in range(leaderboard_count-len(mapinfo_data['top_players'])):
+        mapinfo_data['top_players'].append(('-', '-', '-'))
+
+    for i in range(leaderboard_count-len(mapinfo_data['top_servers'])):
+        mapinfo_data['top_servers'].append(('-', '-', '-'))
+
+    return mapinfo_data
diff --git a/xonstat/views/player.py b/xonstat/views/player.py
index 3a35319..af1337d 100755
--- a/xonstat/views/player.py
+++ b/xonstat/views/player.py
@@ -15,10 +15,7 @@ from xonstat.util import page_url
 log = logging.getLogger(__name__)
 
 
-def player_index(request):
-    """
-    Provides a list of all the current players. 
-    """
+def _player_index_data(request):
     if request.params.has_key('page'):
         current_page = request.params['page']
     else:
@@ -41,7 +38,14 @@ def player_index(request):
            }
 
 
-def get_games_played(player_id):
+def player_index(request):
+    """
+    Provides a list of all the current players.
+    """
+    return _player_index_data(request)
+
+
+def _get_games_played(player_id):
     """
     Provides a breakdown by gametype of the games played by player_id.
 
@@ -64,7 +68,7 @@ def get_games_played(player_id):
 
 # TODO: should probably factor the above function into this one such that
 # total_stats['ctf_games'] is the count of CTF games and so on...
-def get_total_stats(player_id):
+def _get_total_stats(player_id):
     """
     Provides aggregated stats by player_id.
 
@@ -143,10 +147,7 @@ def get_accuracy_stats(player_id, weapon_cd, games):
     return (avg, accs)
 
 
-def player_info(request):
-    """
-    Provides detailed information on a specific player
-    """
+def _player_info_data(request):
     player_id = int(request.matchdict['id'])
     if player_id <= 2:
         player_id = -1;
@@ -156,10 +157,10 @@ def player_info(request):
                 filter(Player.active_ind == True).one()
 
         # games played, alivetime, wins, kills, deaths
-        total_stats = get_total_stats(player.player_id)
+        total_stats = _get_total_stats(player.player_id)
 
         # games breakdown - N games played (X ctf, Y dm) etc
-        (total_games, games_breakdown) = get_games_played(player.player_id)
+        (total_games, games_breakdown) = _get_games_played(player.player_id)
 
 
         # friendly display of elo information and preliminary status
@@ -216,12 +217,14 @@ def player_info(request):
             }
 
 
-def player_game_index(request):
+def player_info(request):
     """
-    Provides an index of the games in which a particular
-    player was involved. This is ordered by game_id, with
-    the most recent game_ids first. Paginated.
+    Provides detailed information on a specific player
     """
+    return _player_info_data(request)
+
+
+def _player_game_index_data(request):
     player_id = request.matchdict['player_id']
 
     if request.params.has_key('page'):
@@ -254,15 +257,17 @@ def player_game_index(request):
             'games':games,
             'pgstats':pgstats}
 
-def player_accuracy(request):
-    """
-    Provides a JSON response representing the accuracy for the given weapon.
 
-    Parameters:
-       weapon = which weapon to display accuracy for. Valid values are 'nex',
-                'shotgun', 'uzi', and 'minstanex'.
-       games = over how many games to display accuracy. Can be up to 50.
+def player_game_index(request):
     """
+    Provides an index of the games in which a particular
+    player was involved. This is ordered by game_id, with
+    the most recent game_ids first. Paginated.
+    """
+    return _player_game_index_data(request)
+
+
+def _player_accuracy_data(request):
     player_id = request.matchdict['id']
     allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
     weapon_cd = 'nex'
@@ -298,3 +303,14 @@ def player_accuracy(request):
             'accs':accs
             }
 
+
+def player_accuracy_json(request):
+    """
+    Provides a JSON response representing the accuracy for the given weapon.
+
+    Parameters:
+       weapon = which weapon to display accuracy for. Valid values are 'nex',
+                'shotgun', 'uzi', and 'minstanex'.
+       games = over how many games to display accuracy. Can be up to 50.
+    """
+    return _player_accuracy_data(request)
diff --git a/xonstat/views/search.py b/xonstat/views/search.py
index 8ce2200..2a791f3 100755
--- a/xonstat/views/search.py
+++ b/xonstat/views/search.py
@@ -74,7 +74,7 @@ def search_q(nick=None, server_name=None, map_name=None, create_dt=None,
 
     return (result_type, q)
 
-def search(request):
+def _search_data(request):
     fs = None
     nick = None
     server_name = None
@@ -145,3 +145,7 @@ def search(request):
             'results':results,
             'query':query,
             }
+
+
+def search(request):
+    return _search_data(request)
diff --git a/xonstat/views/server.py b/xonstat/views/server.py
index daa9885..575d1b0 100755
--- a/xonstat/views/server.py
+++ b/xonstat/views/server.py
@@ -11,10 +11,7 @@ from xonstat.util import page_url, html_colors
 
 log = logging.getLogger(__name__)
 
-def server_index(request):
-    """
-    Provides a list of all the current servers. 
-    """
+def _server_index_data(request):
     if request.params.has_key('page'):
         current_page = request.params['page']
     else:
@@ -33,10 +30,14 @@ def server_index(request):
     return {'servers':servers, }
 
 
-def server_info(request):
+def server_index(request):
     """
-    List the stored information about a given server.
+    Provides a list of all the current servers.
     """
+    return _server_index_data(request)
+
+
+def _server_info_data(request):
     server_id = request.matchdict['id']
 
     try: 
@@ -60,10 +61,7 @@ def server_info(request):
                     (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
                 order_by(expr.desc(func.count())).\
                 group_by(Game.map_id).\
-                group_by(Map.name).all()[0:10]
-
-        for i in range(leaderboard_count-len(top_maps)):
-            top_maps.append(('-', '-', '-'))
+                group_by(Map.name).all()[0:leaderboard_count]
 
         # top players by score
         top_scorers = DBSession.query(Player.player_id, Player.nick, 
@@ -76,14 +74,11 @@ def server_info(request):
                         (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
                 order_by(expr.desc(func.sum(PlayerGameStat.score))).\
                 group_by(Player.nick).\
-                group_by(Player.player_id).all()[0:10]
+                group_by(Player.player_id).all()[0:leaderboard_count]
 
         top_scorers = [(player_id, html_colors(nick), score) \
                 for (player_id, nick, score) in top_scorers]
 
-        for i in range(leaderboard_count-len(top_scorers)):
-            top_scorers.append(('-', '-', '-'))
-
         # top players by playing time
         top_players = DBSession.query(Player.player_id, Player.nick, 
                 func.sum(PlayerGameStat.alivetime)).\
@@ -95,14 +90,11 @@ def server_info(request):
                         (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
                 order_by(expr.desc(func.sum(PlayerGameStat.alivetime))).\
                 group_by(Player.nick).\
-                group_by(Player.player_id).all()[0:10]
+                group_by(Player.player_id).all()[0:leaderboard_count]
 
         top_players = [(player_id, html_colors(nick), score) \
                 for (player_id, nick, score) in top_players]
 
-        for i in range(leaderboard_count-len(top_players)):
-            top_players.append(('-', '-', '-'))
-
         # recent games played in descending order
         recent_games = DBSession.query(Game, Server, Map, PlayerGameStat).\
             filter(Game.server_id==Server.server_id).\
@@ -112,9 +104,6 @@ def server_info(request):
             filter(Server.server_id==server.server_id).\
             order_by(expr.desc(Game.start_dt)).all()[0:recent_games_count]
 
-        for i in range(recent_games_count-len(recent_games)):
-            recent_games.append(('-', '-', '-', '-'))
-
     except Exception as e:
         server = None
         recent_games = None
@@ -128,10 +117,32 @@ def server_info(request):
             }
 
 
-def server_game_index(request):
+def server_info(request):
     """
-    List the games played on a given server. Paginated.
+    List the stored information about a given server.
     """
+    serverinfo_data =  _server_info_data(request)
+
+    # FIXME: code clone, should get these from _server_info_data
+    leaderboard_count = 10
+    recent_games_count = 20
+
+    for i in range(leaderboard_count-len(serverinfo_data['top_maps'])):
+        serverinfo_data['top_maps'].append(('-', '-', '-'))
+
+    for i in range(leaderboard_count-len(serverinfo_data['top_scorers'])):
+        serverinfo_data['top_scorers'].append(('-', '-', '-'))
+
+    for i in range(leaderboard_count-len(serverinfo_data['top_players'])):
+        serverinfo_data['top_players'].append(('-', '-', '-'))
+
+    for i in range(recent_games_count-len(serverinfo_data['recent_games'])):
+        serverinfo_data['recent_games'].append(('-', '-', '-', '-'))
+
+    return serverinfo_data
+
+
+def _server_game_index_data(request):
     server_id = request.matchdict['server_id']
     current_page = request.matchdict['page']
 
@@ -152,3 +163,10 @@ def server_game_index(request):
 
     return {'games':games,
             'server':server}
+
+
+def server_game_index(request):
+    """
+    List the games played on a given server. Paginated.
+    """
+    return _server_game_index_data(request)
-- 
2.39.5