2018-07-07 22:46:28 +00:00
|
|
|
import logging
|
|
|
|
import sqlite3
|
|
|
|
|
|
|
|
import aiohttp
|
|
|
|
from sanic import Sanic, response
|
|
|
|
from sanic_cors import CORS
|
|
|
|
from sanic.exceptions import NotFound, FileNotFound
|
|
|
|
|
|
|
|
import config
|
2018-07-07 23:51:43 +00:00
|
|
|
from elstat import manager
|
2018-07-11 20:00:39 +00:00
|
|
|
from elstat.blueprints import api, streaming
|
2018-07-07 22:46:28 +00:00
|
|
|
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
2018-07-09 05:48:44 +00:00
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
2018-07-07 22:46:28 +00:00
|
|
|
app = Sanic()
|
|
|
|
app.cfg = config
|
|
|
|
CORS(app, automatic_options=True)
|
|
|
|
|
2018-07-09 05:48:44 +00:00
|
|
|
app.blueprint(api)
|
2018-07-10 23:03:07 +00:00
|
|
|
app.blueprint(streaming)
|
2018-07-09 05:48:44 +00:00
|
|
|
|
2018-07-07 22:46:28 +00:00
|
|
|
|
|
|
|
@app.listener('before_server_start')
|
|
|
|
async def _app_start(refapp, loop):
|
|
|
|
refapp.session = aiohttp.ClientSession(loop=loop)
|
|
|
|
refapp.conn = sqlite3.connect('elstat.db')
|
2018-07-09 05:48:44 +00:00
|
|
|
refapp.manager = manager.ServiceManager(app)
|
2018-07-07 22:46:28 +00:00
|
|
|
|
|
|
|
|
|
|
|
@app.listener('after_server_stop')
|
|
|
|
async def _app_stop(refapp, _loop):
|
2018-07-11 05:48:00 +00:00
|
|
|
refapp.manager.close()
|
2018-07-07 22:46:28 +00:00
|
|
|
refapp.conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
@app.exception(Exception)
|
|
|
|
async def _handle_exc(request, exception):
|
2018-07-09 05:48:44 +00:00
|
|
|
log.exception('oopsie woopsie')
|
|
|
|
|
2018-07-07 22:46:28 +00:00
|
|
|
status_code = 404 if isinstance(exception, (NotFound, FileNotFound)) \
|
2018-07-09 05:48:44 +00:00
|
|
|
else 500
|
2018-07-07 22:46:28 +00:00
|
|
|
|
|
|
|
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')
|
|
|
|
|
2018-07-09 20:24:11 +00:00
|
|
|
app.run(port=config.PORT, host='0.0.0.0')
|