#!/usr/bin/env python import errno import json import os from os import path import traceback import warnings warnings.filterwarnings('ignore', 'libevent') import gevent.pywsgi import fileio import reloader DATA_DIR = path.expanduser('~/sysvitals_data') handlers = None def main(): global handlers handlers = { 'data': get_data, 'datum': post_datum, } server = gevent.pywsgi.WSGIServer(('0.0.0.0', 8892), application) reloader.init(server) server.serve_forever() def application(environ, start_response): try: split = environ['PATH_INFO'][1:].split('/') if split[0] == 'v1': handler = handlers.get(split[2]) if handler: body = handler(split, environ) start_response('200 OK', [('Content-type', 'text/plain')]) return [body] else: print 'no handler for', split else: print 'split was', split start_response('404 Not Found', [('Content-type', 'text/plain')]) return ['404 Not Found'] except: traceback.print_exc() start_response('500 Internal Server Error', [('Content-type', 'text/plain')]) return ['ruh roh'] def get_data(split, environ): group = int(split[1]) client_id = int(split[3]) data_path = path.join(DATA_DIR, str(group), str(client_id)) with open(data_path, 'r') as f: stats = fileio.read_stats(f) return json.dumps(stats) def post_datum(split, environ): group = int(split[1]) body = json.load(environ['wsgi.input']) client_id = body['client_id'] group_dir = path.join(DATA_DIR, str(group)) try: os.makedirs(group_dir) except OSError as e: if e.errno != errno.EEXIST: raise with open(path.join(group_dir, str(client_id)), 'w') as f: fileio.write_datum(f, body) return '{"status": "ok"}' main()