From 59924f8021b0fd442c1ba7955e12272aae1217a9 Mon Sep 17 00:00:00 2001 From: Corder Guy Date: Thu, 19 Apr 2018 13:46:51 -0500 Subject: [PATCH] Implement top_n --- mocha_server.py | 51 +++++++++++++++---------------------------------- 1 file changed, 15 insertions(+), 36 deletions(-) diff --git a/mocha_server.py b/mocha_server.py index 69cb3f2..5fad336 100755 --- a/mocha_server.py +++ b/mocha_server.py @@ -11,9 +11,9 @@ DATABASE = '/usr/local/www/mocha-server/mocha.db' if not path.exists(DATABASE): DATABASE = 'mocha.db' -# TODO: Add fetching of top N users by score # TODO: Add ability to store and retrieve avatars (as image files?) + def fetch_users(user_ids): ''' Gets a list of users searching by name. @@ -37,39 +37,6 @@ def fetch_users(user_ids): return output -def get_top_n(search_parameter, desc, num): - ''' - In progress. - Currently the query seems to work, but returning a dict does not - preserve order. - - Store an orderd id list and put that in the json? - - Alternatively, sort on the client-side. - ''' - conn = sqlite3.connect(DATABASE) - conn.row_factory = sqlite3.Row - cursor = conn.cursor() - if desc: - cursor.execute('select * from users order by ? desc limit ?', - (search_parameter, num)) - else: - cursor.execute('select * from users order by ? asc limit ?', - (search_parameter, num)) - - output = cursor.fetchall() - # print(output) - - output = json.dumps([dict(row) for row in output]) - conn.commit() - conn.close() - - if output == '[]': - output = None - - return output - - # add new parameters as needed def update_row(_user_id, _updated_username): ''' @@ -124,7 +91,19 @@ def fetch_top_n(num): ''' Retrieves the top n users by score. ''' - output = get_top_n('score', True, num) + conn = sqlite3.connect(DATABASE) + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + cursor.execute('SELECT * FROM users ORDER BY score DESC') + output = cursor.fetchall() + + output = json.dumps([dict(row) for row in output][:num]) + conn.commit() + conn.close() + + if output == '[]': + output = None + return output @@ -175,7 +154,7 @@ def application(environ, start_response): if __name__ == '__main__': - print(fetch_users(['1', '2', '3'])) + print(fetch_top_n(3)) # vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab