elstat/run.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

54 lines
1.2 KiB
Python

import logging
import sqlite3
import aiohttp
from sanic import Sanic, response
from sanic_cors import CORS
from sanic.exceptions import NotFound, FileNotFound
import config
from elstat import manager
from blueprints import api, streaming
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
app = Sanic()
app.cfg = config
CORS(app, automatic_options=True)
app.blueprint(api)
app.blueprint(streaming)
@app.listener('before_server_start')
async def _app_start(refapp, loop):
refapp.session = aiohttp.ClientSession(loop=loop)
refapp.conn = sqlite3.connect('elstat.db')
refapp.manager = manager.ServiceManager(app)
@app.listener('after_server_stop')
async def _app_stop(refapp, _loop):
refapp.conn.close()
@app.exception(Exception)
async def _handle_exc(request, exception):
log.exception('oopsie woopsie')
status_code = 404 if isinstance(exception, (NotFound, FileNotFound)) \
else 500
return response.json({
'error': True,
'message': repr(exception)
}, status=status_code)
if __name__ == '__main__':
app.static('/', './priv/frontend/build')
app.static('/', './priv/frontend/build/index.html')
app.run(port=config.PORT, host='0.0.0.0')