1
0
mirror of https://github.com/avatao-content/test-tutorial-framework synced 2024-12-05 02:11:32 +00:00

Refactor webservice db stuff to use a single sessionmaker

This commit is contained in:
Kristóf Tóth 2018-05-03 14:24:30 +02:00
parent 3203f3af84
commit 99b19a80da
2 changed files with 18 additions and 19 deletions

View File

@ -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()

View File

@ -39,4 +39,3 @@ class UserOps:
user = User(username=self.username,
passwordhash=PasswordHasher.hash(self.password))
db.add(user)
db.commit()