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
2018-04-10 14:32:36 -05:00

65 lines
1.5 KiB
Python
Executable file

#!/usr/bin/env python3
"""
Handle API requests to the database
"""
import json
import sqlite3
DATABASE = '/usr/local/www/mocha-server/mocha.db'
def fetch(user_id):
"""
Returns a JSON object containing the requested user
Also can return a list of all users if user_id == "*"
"""
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
if user_id != '*':
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.close()
if output is None:
output = ('Error',)
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 = ''
if parts[1] == 'users':
output = fetch(parts[2])
return output
return None
def application(environ, start_response):
"""
mod_wsgi entry point
"""
status = '200 OK'
output = process_request(environ['REQUEST_URI']).encode('UTF-8')
response_headers = [('Content-type', 'application/json'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]