diff --git a/solvable/src/webservice/model.py b/solvable/src/webservice/model.py index 2439684..d722cdc 100644 --- a/solvable/src/webservice/model.py +++ b/solvable/src/webservice/model.py @@ -14,16 +14,17 @@ session_factory = sessionmaker( @contextmanager -def Session(): - session = session_factory() +def Session(factory=session_factory): + session = factory() try: yield session session.commit() except: session.rollback() raise - finally: - session.close() + # session is closed by flask + # finally: + # session.close() Base = declarative_base() diff --git a/solvable/src/webservice/server.py b/solvable/src/webservice/server.py index afeb601..c359c61 100644 --- a/solvable/src/webservice/server.py +++ b/solvable/src/webservice/server.py @@ -1,8 +1,9 @@ from os import urandom, getenv +from functools import partial from flask import Flask, render_template, request, session, url_for, g -from model import init_db, session_factory +from model import init_db, session_factory, Session from user_ops import UserOps from errors import InvalidCredentialsError, UserExistsError @@ -20,6 +21,8 @@ def get_db_session(): g.db_session = session_factory() return g.db_session +Session = partial(Session, get_db_session) + @app.teardown_appcontext def close_db_session(err): # pylint: disable=unused-argument @@ -31,9 +34,12 @@ def close_db_session(err): # pylint: disable=unused-argument def index(): if request.method == 'POST': try: - UserOps(request.form.get('username'), + with Session() as db_session: + UserOps( + request.form.get('username'), request.form.get('password'), - get_db_session()).authenticate() + db_session + ).authenticate() except InvalidCredentialsError: return render_template('login.html', alert='Invalid credentials!') @@ -61,11 +67,12 @@ def register(): return render_template('register.html', alert='Passwords do not match! Please try again.') try: - UserOps( - request.form.get('username'), - request.form.get('password'), - get_db_session() - ).register() + with Session() as db_session: + UserOps( + request.form.get('username'), + request.form.get('password'), + db_session + ).register() except UserExistsError: return render_template('register.html', alert='Username already in use.') diff --git a/solvable/src/webservice/user_ops.py b/solvable/src/webservice/user_ops.py index c7693c7..84831c1 100644 --- a/solvable/src/webservice/user_ops.py +++ b/solvable/src/webservice/user_ops.py @@ -62,6 +62,5 @@ class UserOps: passwordhash=PasswordHasher.hash(self.password) ) self.db_session.add(user) - self.db_session.commit() self.log(f'User "{self.username}" registered!')