Use scoped session

This commit is contained in:
Jeremy Zhang 2018-03-26 18:01:38 +00:00
parent d400c022c1
commit 4820fba2ae

View File

@ -1,7 +1,7 @@
from contextlib import contextmanager from contextlib import contextmanager
import sqlalchemy as db import sqlalchemy as db
from sqlalchemy.engine import Engine, create_engine from sqlalchemy.engine import Engine, create_engine
from sqlalchemy.orm import sessionmaker, Session from sqlalchemy.orm import sessionmaker, Session, scoped_session
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
import json import json
@ -24,21 +24,23 @@ class DatabaseInterface(object):
self.engine = None # type: Engine self.engine = None # type: Engine
self._sessionmaker = None # type: sessionmaker self._sessionmaker = None # type: sessionmaker
self.session = None
def connect(self, dburi): def connect(self, dburi):
self.engine = create_engine(dburi, pool_recycle=10) self.engine = create_engine(dburi, pool_recycle=10)
@contextmanager @contextmanager
def get_session(self): def get_session(self):
Session = sessionmaker(bind=self.engine) SessionMaker = sessionmaker(bind=self.engine)
Session = scoped_session(SessionMaker)
session = Session() session = Session()
try: try:
yield session yield session
session.commit()
except: except:
session.rollback() session.rollback()
finally: finally:
session.close() session.commit()
Session.remove()
async def push_message(self, message): async def push_message(self, message):
if message.guild: if message.guild: