elstat/blueprints/api.py
Luna Mendes 053762f69f
blueprints: add streaming blueprint
clients can connect and subscribe to different channels
and they will get messages from those channels (basic pub/sub)

this is useful in the case of a client wanting issue updates
in real time, which is better than the client having to poll
/api/status every now and then.

 - manager: add ServiceManager.subscribe and .unsub_all
2018-07-10 20:03:07 -03:00

62 lines
1.3 KiB
Python

from sanic import Blueprint, response
bp = Blueprint(__name__)
def get_status(manager):
res = {}
for name, state in manager.state.items():
# ignore unitialized workers
if state is None:
continue
# timestamp will always be the first
worker = manager.workers[name]
columns = worker.adapter.spec['db'][1:]
res[name] = {}
for key, val in zip(columns, state):
res[name][key] = val
res[name]['description'] = worker.service['description']
return res
def get_graphs(manager):
res = {}
for name, worker in manager.workers.items():
# skip adapters without latency
if 'latency' not in worker.adapter.spec['db']:
continue
cur = manager.conn.cursor()
cur.execute(f"""
SELECT timestamp, latency FROM {name}
ORDER BY timestamp DESC
LIMIT 50
""")
qres = cur.fetchall()
res[name] = qres
return res
@bp.get('/api/current_status')
async def get_cur_status(request):
manager = request.app.manager
return response.json(get_status(manager))
@bp.get('/api/status')
async def get_full_status(request):
manager = request.app.manager
return response.json({
'status': get_status(manager),
'graph': get_graphs(manager),
})