#!/usr/bin/env python3 """ Handle API requests to the database """ import json import sqlite3 from os import path # NOTE: closing a database makes the next query in a script not work DATABASE = '/usr/local/www/mocha-server/mocha.db' if not path.exists(DATABASE): DATABASE = 'mocha.db' conn = sqlite3.connect(DATABASE) conn.row_factory = sqlite3.Row cursor = conn.cursor() # TODO: Add fetching of list of users # TODO: Add fetching of top N users by score # TODO: Add ability to store and retrieve avatars (as image files?) def get_users(username_list): """ Gets a list of users searching by name. This can also easily be done by user_id. """ output = [] for usr in username_list: cursor.execute("select * from users where username=(?)", (usr,)) output += cursor.fetchall() output = json.dumps([dict(row) for row in output]) conn.commit() #conn.close() if output == '[]': output = None return output def get_top_N(search_parameter, desc, N): """ 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? """ if desc == True: cursor.execute("select * from users order by ? desc limit ?", (search_parameter, N)) else: cursor.execute("select * from users order by ? asc limit ?", (search_parameter, N)) 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): print() def insert_row(user_id, username): """ Inserts a row for a NEW user with given parameters This may work better with AUTOINCREMENT to avoid arbitrary ids and duplicates """ cursor.execute("insert into users values (?,?)", (user_id, username)) conn.commit() #conn.close() def fetch_user(user_id): """ Returns a JSON object containing the requested user Also can return a list of all users if user_id == "*" """ if user_id != '*': # must use (?), (item,) format cursor.execute("SELECT * FROM users WHERE user_id=(?)", (user_id,)) else: cursor.execute("SELECT * FROM users") output = cursor.fetchall() output = json.dumps([dict(row) for row in output]) conn.commit() #conn.close() if output == '[]': output = None return output def process_request(uri): """ Handles the API endpoint. Currently supports: - /mocha/users/"user_id" Returns JSON of the specified user - /mocha/users/* Returns JSON list of all users """ parts = uri.split('/')[1:] assert parts[0] == 'mocha' output = None if parts[1] == 'users': output = fetch_user(parts[2]) return output def application(environ, start_response): """ mod_wsgi entry point """ status = '200 OK' output = process_request(environ['REQUEST_URI']) if output is None: status = '404 Not Found' output = '' output = output.encode('UTF-8') response_headers = [('Content-type', 'application/json'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output]