sqlalchemy.orm.session.Session

Here are the examples of the python api sqlalchemy.orm.session.Session taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

19 Examples 7

Example 1

Project: iktomi Source File: types.py
Function: test_string_list
    def test_string_list(self):
        words = ['one', 'two', 'three', 'four', 'five']
        obj = TypesObject()
        obj.words = words
        self.db.add(obj)
        self.db.commit()

        self.db.close()
        self.db = Session(bind=self.engine)
        obj = self.db.query(TypesObject).first()
        self.assertEqual(words, obj.words)

Example 2

Project: iktomi Source File: types.py
    def test_integer_list(self):
        numbers = [1, 5, 10, 15, 20]
        obj = TypesObject()
        obj.numbers = numbers
        self.db.add(obj)
        self.db.commit()

        self.db.close()
        self.db = Session(bind=self.engine)
        obj = self.db.query(TypesObject).first()
        self.assertEqual(numbers, obj.numbers)

Example 3

Project: iktomi Source File: types.py
    def test_string_wrapped_in_html(self):
        obj = TypesObject()
        obj.html_string1 = Markupable('<html>value</html>')
        self.db.add(obj)
        self.db.commit()
        self.db.close()

        self.db = Session(bind=self.engine)
        obj = self.db.query(TypesObject).first()
        self.assertIsInstance(obj.html_string1, Markup)
        self.assertEqual('<html>value</html>', obj.html_string1)

Example 4

Project: iktomi Source File: types.py
Function: test_html_string
    def test_html_string(self):
        obj = TypesObject()
        obj.html_string2 = Markupable('<html>value</html>')
        self.db.add(obj)
        self.db.commit()
        self.db.close()

        self.db = Session(bind=self.engine)
        obj = self.db.query(TypesObject).first()
        self.assertIsInstance(obj.html_string2, Markup)
        self.assertEqual('<html>value</html>', obj.html_string2)

Example 5

Project: iktomi Source File: types.py
    def test_html_text(self):
        obj = TypesObject()
        text = "<html>" + "the sample_text " * 100 + "</html>"
        obj.html_text = Markupable(text)
        self.db.add(obj)
        self.db.commit()
        self.db.close()

        self.db = Session(bind=self.engine)
        obj = self.db.query(TypesObject).first()
        self.assertIsInstance(obj.html_text, Markup)
        self.assertEqual(text, obj.html_text)

Example 6

Project: iktomi Source File: types.py
    def test_html_custom_markup(self):
        obj = TypesObject()
        obj.html_custom = Markupable('<html>   value   </html>')
        self.db.add(obj)
        self.db.commit()
        self.db.close()

        self.db = Session(bind=self.engine)
        obj = self.db.query(TypesObject).first()
        self.assertIsInstance(obj.html_custom, CustomMarkup)
        self.assertEqual('<html> value </html>', obj.html_custom)

Example 7

Project: marcotti Source File: conftest.py
Function: session
@pytest.fixture()
def session(request, db_connection):
    __transaction = db_connection.begin_nested()
    session = Session(db_connection)

    def fin():
        session.close()
        __transaction.rollback()
    request.addfinalizer(fin)
    return session

Example 8

Project: marcotti Source File: interface.py
Function: create_session
    @contextmanager
    def create_session(self):
        """
        Create a session context that communicates with the database.

        Commits all changes to the database before closing the session, and if an exception is raised,
        rollback the session.
        """
        session = Session(self.connection)
        try:
            yield session
            session.commit()
        except Exception as ex:
            session.rollback()
            raise ex
        finally:
            session.close()

Example 9

Project: cruzdb Source File: sqlsoup.py
    @property
    def _underlying_session(self):
        if isinstance(self.session, session.Session):
            return self.session
        else:
            return self.session()

Example 10

Project: sqlalchemy-continuum Source File: test_sessions.py
Function: test_multiple_connections
    def test_multiple_connections(self):
        self.session2 = Session(bind=self.engine.connect())
        article = self.Article(name=u'Session1 article')
        article2 = self.Article(name=u'Session2 article')
        self.session.add(article)
        self.session2.add(article2)
        self.session.flush()
        self.session2.flush()

        self.session.commit()
        self.session2.commit()
        assert article.versions[-1].transaction_id
        assert (
            article2.versions[-1].transaction_id >
            article.versions[-1].transaction_id
        )

Example 11

Project: sqlalchemy-continuum Source File: test_sessions.py
    def test_connection_binded_to_engine(self):
        self.session2 = Session(bind=self.engine)
        article = self.Article(name=u'Session1 article')
        self.session2.add(article)
        self.session2.commit()
        assert article.versions[-1].transaction_id

Example 12

Project: sync-engine Source File: session.py
def two_phase_session(engine_map, versioned=True):
    """
    Returns a session that implements two-phase-commit.
    Parameters
    ----------
    engine_map: dict
    Mapping of Table cls instance: database engine

    versioned: bool

    """
    session = Session(binds=engine_map, twophase=True, autoflush=True,
                      autocommit=False)
    if versioned:
        session = configure_versioning(session)
        # TODO[k]: Metrics for transaction latencies!
    return session

Example 13

Project: cloudkitty Source File: test_storage.py
    def test_create_session_on_append(self):
        self.assertNotIn(self._tenant_id, self.storage._session)
        working_data = copy.deepcopy(samples.RATED_DATA)
        self.storage.append(working_data, self._tenant_id)
        self.assertIn(self._tenant_id, self.storage._session)
        self.assertIsInstance(
            self.storage._session[self._tenant_id],
            sqlalchemy.orm.session.Session)

Example 14

Project: iktomi Source File: types.py
Function: set_up
    def setUp(self):
        self.engine = create_engine("sqlite://")
        Base.metadata.create_all(self.engine)
        self.db = Session(bind=self.engine)

Example 15

Project: sqlalchemy-continuum Source File: unit_of_work.py
    def process_before_flush(self, session):
        """
        Before flush processor for given session.

        This method creates a version session which is later on used for the
        creation of version objects. It also creates Transaction object for the
        current transaction and invokes before_flush template method on all
        plugins.

        If the given session had no relevant modifications regarding versioned
        objects this method does nothing.

        :param session: SQLAlchemy session object
        """
        if session == self.version_session:
            return

        if not self.is_modified(session):
            return

        if not self.version_session:
            self.version_session = sa.orm.session.Session(
                bind=session.connection()
            )

        if not self.current_transaction:
            self.create_transaction(session)

        self.manager.plugins.before_flush(self, session)

Example 16

Project: sqlalchemy-continuum Source File: unit_of_work.py
    def process_after_flush(self, session):
        """
        After flush processor for given session.

        Creates version objects for all modified versioned parent objects that
        were affected during the flush phase.

        :param session: SQLAlchemy session object
        """
        if session == self.version_session:
            return

        if not self.current_transaction:
            return

        if not self.version_session:
            self.version_session = sa.orm.session.Session(
                bind=session.connection()
            )

        self.make_versions(session)

Example 17

Project: sqlalchemy-continuum Source File: unit_of_work.py
Function: create_transaction
    def create_transaction(self, session):
        """
        Create transaction object for given SQLAlchemy session.

        :param session: SQLAlchemy session object
        """
        args = self.transaction_args(session)

        Transaction = self.manager.transaction_cls
        self.current_transaction = Transaction()

        for key, value in args.items():
            setattr(self.current_transaction, key, value)
        if not self.version_session:
            self.version_session = sa.orm.session.Session(
                bind=session.connection()
            )
        self.version_session.add(self.current_transaction)
        self.version_session.flush()
        self.version_session.expunge(self.current_transaction)
        session.add(self.current_transaction)
        return self.current_transaction

Example 18

Project: sync-engine Source File: session.py
def new_session(engine, versioned=True):
    """Returns a session bound to the given engine."""
    session = Session(bind=engine, autoflush=True, autocommit=False)

    if versioned:
        configure_versioning(session)

        # Make statsd calls for transaction times
        transaction_start_map = {}
        frame, modname = find_first_app_frame_and_name(
            ignores=['sqlalchemy', 'inbox.models.session', 'nylas.logging',
                     'contextlib'])
        funcname = frame.f_code.co_name
        modname = modname.replace(".", "-")
        metric_name = 'db.{}.{}.{}'.format(engine.url.database, modname,
                                           funcname)

        @event.listens_for(session, 'after_begin')
        def after_begin(session, transaction, connection):
            # It's okay to key on the session object here, because each session
            # binds to only one engine/connection. If this changes in the
            # future such that a session may encompass multiple engines, then
            # we'll have to get more sophisticated.
            transaction_start_map[session] = time.time()

        @event.listens_for(session, 'after_commit')
        @event.listens_for(session, 'after_rollback')
        def end(session):
            start_time = transaction_start_map.get(session)
            if not start_time:
                return

            del transaction_start_map[session]

            t = time.time()
            latency = int((t - start_time) * 1000)
            statsd_client.timing(metric_name, latency)
            statsd_client.incr(metric_name)
            if latency > MAX_SANE_TRX_TIME_MS:
                log.warning('Long transaction', latency=latency,
                            modname=modname, funcname=funcname)

    return session

Example 19

Project: blazar Source File: session.py
def _wrap_db_error(f):
    @functools.wraps(f)
    def _wrap(self, *args, **kwargs):
        try:
            assert issubclass(
                self.__class__, sqlalchemy.orm.session.Session
            ), ('_wrap_db_error() can only be applied to methods of '
                'subclasses of sqlalchemy.orm.session.Session.')

            return f(self, *args, **kwargs)
        except UnicodeEncodeError:
            raise exception.DBInvalidUnicodeParameter()
        except sqla_exc.OperationalError as e:
            _raise_if_db_connection_lost(e, self.bind)
            _raise_if_deadlock_error(e, self.bind.dialect.name)
            # NOTE(comstud): A lot of code is checking for OperationalError
            # so let's not wrap it for now.
            raise
        # note(boris-42): We should catch unique constraint violation and
        # wrap it by our own DBDuplicateEntry exception. Unique constraint
        # violation is wrapped by IntegrityError.
        except sqla_exc.IntegrityError as e:
            # note(boris-42): SqlAlchemy doesn't unify errors from different
            # DBs so we must do this. Also in some tables (for example
            # instance_types) there are more than one unique constraint. This
            # means we should get names of columns, which values violate
            # unique constraint, from error message.
            _raise_if_duplicate_entry_error(e, self.bind.dialect.name)
            raise exception.DBError(e)
        except Exception as e:
            LOG.exception(_LE('DB exception wrapped.'))
            raise exception.DBError(e)
    return _wrap