This repository has been archived on 2025-04-11. You can view files and clone it, but cannot push or open issues or pull requests.
mochaserverpine64backup/mocha_server.py

155 lines
3.5 KiB
Python
Raw Normal View History

2018-04-08 23:48:07 -05:00
#!/usr/bin/env python3
2018-04-10 14:32:36 -05:00
"""
Handle API requests to the database
2018-04-10 14:26:40 -05:00
"""
2018-04-08 23:48:07 -05:00
import json
import sqlite3
2018-04-17 13:43:45 -05:00
from os import path
2018-04-08 23:48:07 -05:00
2018-04-17 12:31:13 -05:00
# NOTE: closing a database makes the next query in a script not work
2018-04-08 23:48:07 -05:00
2018-04-17 13:43:45 -05:00
DATABASE = '/usr/local/www/mocha-server/mocha.db'
if not path.exists(DATABASE):
DATABASE = 'mocha.db'
2018-04-17 10:17:17 -05:00
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
2018-04-10 15:24:15 -05:00
# 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?)
2018-04-08 23:48:07 -05:00
2018-04-17 12:31:13 -05:00
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):
2018-04-17 10:46:32 -05:00
"""
2018-04-17 12:31:13 -05:00
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?
2018-04-17 10:46:32 -05:00
"""
2018-04-17 12:31:13 -05:00
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])
2018-04-17 10:46:32 -05:00
conn.commit()
2018-04-17 12:31:13 -05:00
#conn.close()
if output == '[]':
output = None
return output
2018-04-17 10:46:32 -05:00
2018-04-17 10:17:17 -05:00
# add new parameters as needed
def update_row(user_id, updated_username):
print()
2018-04-17 12:31:13 -05:00
2018-04-17 10:17:17 -05:00
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
"""
2018-04-17 10:46:32 -05:00
cursor.execute("insert into users values (?,?)", (user_id, username))
2018-04-17 10:17:17 -05:00
conn.commit()
2018-04-17 12:31:13 -05:00
#conn.close()
2018-04-17 10:17:17 -05:00
2018-04-10 15:24:15 -05:00
def fetch_user(user_id):
2018-04-10 14:32:36 -05:00
"""
Returns a JSON object containing the requested user
Also can return a list of all users if user_id == "*"
"""
2018-04-08 23:48:07 -05:00
2018-04-17 10:17:17 -05:00
if user_id != '*': # must use (?), (item,) format
cursor.execute("SELECT * FROM users WHERE user_id=(?)", (user_id,))
2018-04-08 23:48:07 -05:00
else:
2018-04-10 14:26:40 -05:00
cursor.execute("SELECT * FROM users")
2018-04-08 23:48:07 -05:00
2018-04-10 14:26:40 -05:00
output = cursor.fetchall()
2018-04-08 23:48:07 -05:00
output = json.dumps([dict(row) for row in output])
2018-04-17 12:31:13 -05:00
conn.commit()
#conn.close()
2018-04-08 23:48:07 -05:00
2018-04-10 15:29:00 -05:00
if output == '[]':
output = None
2018-04-08 23:48:07 -05:00
return output
2018-04-17 14:24:04 -05:00
def fetch_top_n(n):
output = get_top_N('score', True, n)
if output == '[]':
output = None
return output
2018-04-08 23:48:07 -05:00
def process_request(uri):
2018-04-10 14:32:36 -05:00
"""
Handles the API endpoint.
Currently supports:
- /mocha/users/"user_id" Returns JSON of the specified user
- /mocha/users/* Returns JSON list of all users
"""
2018-04-08 23:48:07 -05:00
parts = uri.split('/')[1:]
assert parts[0] == 'mocha'
2018-04-10 15:29:00 -05:00
output = None
2018-04-08 23:48:07 -05:00
if parts[1] == 'users':
2018-04-10 15:24:15 -05:00
output = fetch_user(parts[2])
2018-04-17 14:24:04 -05:00
elif parts[1] == 'top':
output = fetch_top_n(parts[2])
2018-04-10 15:24:15 -05:00
return output
2018-04-08 23:48:07 -05:00
2018-04-06 00:31:31 -05:00
def application(environ, start_response):
2018-04-10 14:32:36 -05:00
"""
mod_wsgi entry point
"""
2018-04-06 00:31:31 -05:00
status = '200 OK'
2018-04-10 15:24:15 -05:00
output = process_request(environ['REQUEST_URI'])
if output is None:
status = '404 Not Found'
output = ''
output = output.encode('UTF-8')
2018-04-06 00:31:31 -05:00
2018-04-08 23:48:07 -05:00
response_headers = [('Content-type', 'application/json'),
2018-04-06 00:31:31 -05:00
('Content-Length', str(len(output)))]
2018-04-10 15:24:15 -05:00
2018-04-06 00:31:31 -05:00
start_response(status, response_headers)
return [output]