iro/model/utils.py
author Sandro Knauß <knauss@netzguerilla.net>
Thu, 29 Mar 2012 17:21:46 +0200
branchdevel
changeset 259 5d9c24c2cb8d
parent 122 b55754aa4f96
child 261 6b28b135a919
permissions -rw-r--r--
iro.model.utils: adding docstrings

from sqlalchemy.orm import sessionmaker

from .session import IroSession
class WithSession(object):
    '''a with statement for a database session connection.'''
    def __init__(self, engine, autocommit=False):
        """
        :param `sqlalchemy.engine.base.Engine` engine: a valid sqlalchemy engine object (normally created via :func:`sqlalchemy.create_engine`).
        :param boolean autocommit: autocommit after running the function.

        .. automethod:: __enter__
        """
        self.engine = engine
        self.autocommit=autocommit
    
    def __enter__(self):
        self.session = sessionmaker(bind=self.engine, class_ = IroSession)()
        """returns a vaild session object"""
        self.session = sessionmaker(bind=self.engine)()
        return self.session
    
    def __exit__(self,exc_type, exc_value, traceback):
        if exc_type is None:
            if self.autocommit:
                self.session.commit()
        else:
            self.session.rollback()
        self.session.close()