From 99b19a80da63999d8c199739c304e28818407f8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Thu, 3 May 2018 14:24:30 +0200 Subject: [PATCH] Refactor webservice db stuff to use a single sessionmaker --- solvable/src/webservice/model.py | 36 ++++++++++++++--------------- solvable/src/webservice/user_ops.py | 1 - 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/solvable/src/webservice/model.py b/solvable/src/webservice/model.py index efdaf86..f135b25 100644 --- a/solvable/src/webservice/model.py +++ b/solvable/src/webservice/model.py @@ -1,9 +1,27 @@ +from contextlib import contextmanager + from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///db.db', convert_unicode=True) +session_factory = sessionmaker(autocommit=False, + autoflush=False, + bind=engine) + + +@contextmanager +def Session(): + session = session_factory() + try: + yield session + session.commit() + except: + session.rollback() + raise + finally: + session.close() Base = declarative_base() @@ -19,21 +37,3 @@ class User(Base): def init_db(): Base.metadata.create_all(bind=engine) - - -class Session: - session = None - - def __enter__(self): - self.session = Session.create() - return self.session - - @staticmethod - def create(): - factory = sessionmaker(autocommit=False, - autoflush=False, - bind=engine) - return factory() - - def __exit__(self, exc_type, exc_val, exc_tb): - self.session.close() diff --git a/solvable/src/webservice/user_ops.py b/solvable/src/webservice/user_ops.py index ba6bbd3..2472255 100644 --- a/solvable/src/webservice/user_ops.py +++ b/solvable/src/webservice/user_ops.py @@ -39,4 +39,3 @@ class UserOps: user = User(username=self.username, passwordhash=PasswordHasher.hash(self.password)) db.add(user) - db.commit()