mirror of
https://github.com/avatao-content/test-tutorial-framework
synced 2024-11-15 01:27:18 +00:00
Refactor webservice db stuff to use a single sessionmaker
This commit is contained in:
parent
3203f3af84
commit
99b19a80da
@ -1,9 +1,27 @@
|
|||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
from sqlalchemy import Column, Integer, String, create_engine
|
from sqlalchemy import Column, Integer, String, create_engine
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
|
|
||||||
engine = create_engine('sqlite:///db.db', convert_unicode=True)
|
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()
|
Base = declarative_base()
|
||||||
@ -19,21 +37,3 @@ class User(Base):
|
|||||||
|
|
||||||
def init_db():
|
def init_db():
|
||||||
Base.metadata.create_all(bind=engine)
|
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()
|
|
||||||
|
@ -39,4 +39,3 @@ class UserOps:
|
|||||||
user = User(username=self.username,
|
user = User(username=self.username,
|
||||||
passwordhash=PasswordHasher.hash(self.password))
|
passwordhash=PasswordHasher.hash(self.password))
|
||||||
db.add(user)
|
db.add(user)
|
||||||
db.commit()
|
|
||||||
|
Loading…
Reference in New Issue
Block a user