Implement top_n
This commit is contained in:
parent
d0da00c8e4
commit
59924f8021
1 changed files with 15 additions and 36 deletions
|
@ -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
|
||||
|
|
Reference in a new issue