There will be a short maintenance break on Wed 27.10. at 12:00. Estimated time 30 minutes.

Commit c77bf75b authored by Ossi Laine's avatar Ossi Laine
Browse files

Close db session manually after socket connection has ended

parent 4a8848e6
...@@ -68,10 +68,6 @@ def get_locale(): ...@@ -68,10 +68,6 @@ def get_locale():
""" """
# Run flask app with socketIO
socketio = SocketIO(app, cors_allowed_origins="*")
# socketio = SocketIO()
socketio.init_app(app)
#mariabd mysql portti 3306 tarkista? #mariabd mysql portti 3306 tarkista?
...@@ -82,6 +78,11 @@ migrate = Migrate(app, db) ...@@ -82,6 +78,11 @@ migrate = Migrate(app, db)
login = LoginManager(app) login = LoginManager(app)
login.login_view = 'login' login.login_view = 'login'
# Run flask app with socketIO
socketio = SocketIO(app, cors_allowed_origins="*")
# socketio = SocketIO()
socketio.init_app(app)
# Register blueprints # Register blueprints
from .task.views import task_blueprint from .task.views import task_blueprint
from .experiment.views import experiment_blueprint from .experiment.views import experiment_blueprint
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
import os import os
import secrets import secrets
from datetime import date from datetime import date
from tempfile import mkstemp
from flask_socketio import emit from flask_socketio import emit
from sqlalchemy import and_ from sqlalchemy import and_
...@@ -13,7 +14,8 @@ from flask import ( ...@@ -13,7 +14,8 @@ from flask import (
flash, flash,
redirect, redirect,
url_for, url_for,
Blueprint Blueprint,
send_file
) )
from app import app, db, socketio from app import app, db, socketio
...@@ -1045,7 +1047,7 @@ def remove_rows(rows): ...@@ -1045,7 +1047,7 @@ def remove_rows(rows):
@socketio.on('connect', namespace="/create_embody") @socketio.on('connect', namespace="/create_embody")
def create_embody(): def start_create_embody():
emit('success', {'connection': 'on'}) emit('success', {'connection': 'on'})
...@@ -1059,47 +1061,39 @@ def create_embody(meta): ...@@ -1059,47 +1061,39 @@ def create_embody(meta):
@socketio.on('end', namespace="/create_embody") @socketio.on('end', namespace="/create_embody")
def create_embody(): def end_create_embody():
emit('end', {'connection': 'off'}) db.session.close()
@socketio.on('connect', namespace="/download_csv") @socketio.on('connect', namespace="/download_csv")
def create_embody(): def start_download_csv():
emit('success', {'connection': 'Start generating CSV file'}) emit('success', {'connection': 'Start generating CSV file'})
from tempfile import mkstemp
from flask import send_file
@socketio.on('generate_csv', namespace="/download_csv") @socketio.on('generate_csv', namespace="/download_csv")
def create_embody(meta): def process_download_csv(meta):
exp_id = meta["exp_id"] exp_id = meta["exp_id"]
data = generate_csv(exp_id) data = generate_csv(exp_id)
# error handling
if isinstance(data, Exception): if isinstance(data, Exception):
emit('timeout', {'exc': str(data)}) emit('timeout', {'exc': str(data)})
return return
filename = "experiment_{}_{}".format( # create temporary file
exp_id, date.today().strftime("%Y-%m-%d"))
fd, path = mkstemp() fd, path = mkstemp()
print(fd)
print(path)
with os.fdopen(fd, 'w') as tmp: with os.fdopen(fd, 'w') as tmp:
tmp.write(data) tmp.write(data)
tmp.flush() tmp.flush()
# return path and filename to front so user can start downloading
filename = "experiment_{}_{}".format(
exp_id, date.today().strftime("%Y-%m-%d"))
path = path.split('/')[-1] path = path.split('/')[-1]
emit('file_ready', {'path': path, 'filename': filename}) emit('file_ready', {'path': path, 'filename': filename})
# return saved_data_as_file(filename, csv)
@socketio.on('end', namespace="/download_csv")
def end_download_csv():
db.session.close()
...@@ -26,6 +26,7 @@ $(document).ready(function()  { ...@@ -26,6 +26,7 @@ $(document).ready(function()  {
socket.on('timeout', function(data) { socket.on('timeout', function(data) {
// kill connection // kill connection
socket.emit('end')
socket.disconnect() socket.disconnect()
exportButton.text('Export results') exportButton.text('Export results')
......
...@@ -19,6 +19,8 @@ $(document).ready(function()  { ...@@ -19,6 +19,8 @@ $(document).ready(function()  {
}); });
socket.on('end', function(img) { socket.on('end', function(img) {
// kill connection
socket.emit('end')
socket.disconnect() socket.disconnect()
// Draw image to statistic -page // Draw image to statistic -page
......
...@@ -124,6 +124,8 @@ def timeit(method): ...@@ -124,6 +124,8 @@ def timeit(method):
def get_coordinates(idpage, idembody=None, select_clause=SELECT_BY_PAGE_AND_PICTURE): def get_coordinates(idpage, idembody=None, select_clause=SELECT_BY_PAGE_AND_PICTURE):
"""Select all drawn points from certain stimulus and plot them onto """Select all drawn points from certain stimulus and plot them onto
the human body""" the human body"""
# init db
db = MyDB() db = MyDB()
db.query(select_clause, (idpage,idembody)) db.query(select_clause, (idpage,idembody))
...@@ -141,6 +143,9 @@ def get_coordinates(idpage, idembody=None, select_clause=SELECT_BY_PAGE_AND_PICT ...@@ -141,6 +143,9 @@ def get_coordinates(idpage, idembody=None, select_clause=SELECT_BY_PAGE_AND_PICT
else: else:
plt = plot_coordinates(coordinates, DEFAULT_IMAGE_PATH) plt = plot_coordinates(coordinates, DEFAULT_IMAGE_PATH)
# close db connection
db.__del__()
# Save image to ./app/static/ # Save image to ./app/static/
img_filename = 'PAGE-' + str(idpage) + '-' + DATE_STRING + '.png' img_filename = 'PAGE-' + str(idpage) + '-' + DATE_STRING + '.png'
plt.savefig(STATIC_PATH + img_filename) plt.savefig(STATIC_PATH + img_filename)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment