Вы можете создать простую функцию вне класса, чтобы обернуть каждый метод:
def create_session(**kwargs):
def outer(f):
def wrapper(cls, *args):
Session = sessionmaker(bind=getattr(cls, 'engine'))
session = Session()
getattr(session, kwargs.get('action', 'add'))(f(cls, *args))
session.commit()
session.close()
return wrapper
return outer
class UserDatabaseManager(object):
DEFAULT_DB_PATH = 'test.db'
def __init__(self, dbpath=DEFAULT_DB_PATH):
dbpath = 'sqlite:///' + dbpath
self.engine = create_engine(dbpath, echo=True)
@create_session(action = 'add')
def add_user(self, username, password):
return User(username, password)
@create_session(action = 'delete')
def delete_user(self, user):
return User(username, password)
Как правило, операции настройки и удаления, подобные описанным выше, лучше всего помещать в менеджер контекста:
class UserDatabaseManager(object):
DEFAULT_DB_PATH = 'test.db'
def __init__(self, dbpath=DEFAULT_DB_PATH):
dbpath = 'sqlite:///' + dbpath
self.engine = create_engine(dbpath, echo=True)
class UserAction(UserDatabaseManager):
def __init__(self, path):
UserDatabaseManager.__init__(self, path)
def __enter__(self):
self.session = sessionmaker(bind=self.engine)()
return self.session
def __exit__(self, *args):
self.session.commit()
self.session.close()
with UserAction('/the/path') as action:
action.add(User(username, password))
with UserAction('/the/path') as action:
action.remove(User(username, password))