iro/model/utils.py
author Sandro Knauß <knauss@netzguerilla.net>
Wed, 25 Apr 2012 15:06:28 +0200
branchdevel
changeset 277 f65edc0382cc
parent 262 212a69cc4d44
child 294 0e75bd39767d
permissions -rw-r--r--
prepare for release: * diffrent web directory with all web specific content (split doc dir -> doc (data) and web (rendered data)) * update installation

from sqlalchemy.orm import sessionmaker

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__
        .. automethod:: __exit__
        """
        self.engine = engine
        self.autocommit=autocommit
    
    def __enter__(self):
        """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()