Ver código fonte

api: get data

raylu 11 anos atrás
pai
commit
a8f2e05c7f
1 arquivos alterados com 40 adições e 3 exclusões
  1. 40 3
      api/server.py

+ 40 - 3
api/server.py

@@ -28,7 +28,43 @@ formats = {
 	'net': 'l',
 	'disk': 'l',
 }
-def datum(split, environ):
+
+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:
+		buf = f.read()
+	rval = {}
+	index = 0
+	while index < len(buf):
+		# read the key
+		key_size = ord(buf[index])
+		fmt = '%dp' % (key_size + 1)
+		data = struct.unpack(fmt, buf[index:index+key_size+1])
+		key = data[0]
+
+		# get the format_code
+		split = key.split('.')
+		stat_group = split[0]
+		format_code = formats[stat_group]
+
+		# read the data
+		fmt = '%dp 1440%s' % (key_size + 1, format_code)
+		size = struct.calcsize(fmt)
+		data = struct.unpack(fmt, buf[index:index+size])
+		dict_insert(rval, split, data[1:])
+		index += size
+	return json.dumps(rval)
+
+def dict_insert(d, split, value):
+	if len(split) > 1:
+		d.setdefault(split[0], {})
+		dict_insert(d[split[0]], split[1:], value)
+	else:
+		d[split[0]] = value
+
+def post_datum(split, environ):
 	group = int(split[1])
 	body = json.load(environ['wsgi.input'])
 	client_id = body['client_id']
@@ -50,12 +86,13 @@ def datum(split, environ):
 
 def write_stat(f, key, format_code, data):
 	fmt = '%dp 1440%s' % (len(key) + 1, format_code)
-	array = [0] * 1440
+	array = [-1] * 1440
 	array[0] = data
 	f.write(struct.pack(fmt, key, *array))
 
 handlers = {
-	'datum': datum,
+	'data': get_data,
+	'datum': post_datum,
 }
 
 server = gevent.pywsgi.WSGIServer(('0.0.0.0', 8892), application)