sqlalchemy.event.listen

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

200 Examples 7

Example 1

Project: king-phisher
Source File: models.py
View license
def register_table(table):
	"""
	Register a database table. This will populate the information provided in
	DATABASE_TABLES dictionary. This also forwards signals to the appropriate
	listeners within the :py:mod:`server.signal` module.

	:param cls table: The table to register.
	"""
	columns = tuple(col.name for col in table.__table__.columns)
	database_tables[table.__tablename__] = columns
	database_table_objects[table.__tablename__] = table

	sqlalchemy.event.listen(table, 'before_delete', forward_signal_delete)
	sqlalchemy.event.listen(table, 'before_insert', forward_signal_insert)
	sqlalchemy.event.listen(table, 'before_update', forward_signal_update)
	return table

Example 2

Project: king-phisher
Source File: models.py
View license
def register_table(table):
	"""
	Register a database table. This will populate the information provided in
	DATABASE_TABLES dictionary. This also forwards signals to the appropriate
	listeners within the :py:mod:`server.signal` module.

	:param cls table: The table to register.
	"""
	columns = tuple(col.name for col in table.__table__.columns)
	database_tables[table.__tablename__] = columns
	database_table_objects[table.__tablename__] = table

	sqlalchemy.event.listen(table, 'before_delete', forward_signal_delete)
	sqlalchemy.event.listen(table, 'before_insert', forward_signal_insert)
	sqlalchemy.event.listen(table, 'before_update', forward_signal_update)
	return table

Example 3

Project: Flexget
Source File: debug_db_sessions.py
View license
@event('manager.startup')
def debug_warnings(manager):
    if manager.options.debug_db_sessions:
        sqlalchemy.event.listen(Session, 'after_begin', after_begin)
        sqlalchemy.event.listen(Session, 'after_flush', after_flush)
        sqlalchemy.event.listen(Session, 'after_transaction_end', after_end)

Example 4

Project: sqlalchemy-media
Source File: stores.py
View license
    def bind_events(self) -> None:
        """
        Binds the required event on sqlalchemy session. to handle commit & rollback.

        """
        event.listen(self.session, 'after_commit', self.on_commit)
        event.listen(self.session, 'after_soft_rollback', self.on_rollback)
        event.listen(self.session, 'persistent_to_deleted', self.on_delete)

Example 5

Project: raggregate
Source File: __init__.py
View license
def initialize_sql_test(engine):
    DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all(engine)
    listen(sqlalchemy.orm.mapper, 'before_insert', make_uuid)
    return [DBSession, Base]

Example 6

Project: iktomi
Source File: files.py
View license
    def instrument_class(self, mapper):
        handlers = self.event_cls(self)
        event.listen(mapper, 'before_insert', handlers.before_insert,
                     propagate=True)
        event.listen(mapper, 'before_update', handlers.before_update,
                     propagate=True)
        event.listen(mapper, 'after_delete', handlers.after_delete,
                     propagate=True)
        setattr(mapper.class_, self.key,
                self.attribute_cls(self, mapper.class_))

Example 7

Project: tvb-framework
Source File: db_events.py
View license
def attach_db_events():   
    """
    Attach events to all mapped tables.
    """
    event.listen(mapper, EVENT_LOAD, initialize_on_load)
    event.listen(mapper, EVENT_BEFORE_INSERT, fill_before_insert)

Example 8

Project: python-sync-db
Source File: tracking.py
View license
def _start_tracking(model, directions):
    if 'pull' in directions:
        core.pulled_models.add(model)
    if 'push' in directions:
        core.pushed_models.add(model)
    if model in core.synched_models.models:
        return model
    core.synched_models.install(model)
    if 'push' not in directions:
        return model # don't track operations for pull-only models
    event.listen(model, 'after_insert', make_listener('i'))
    event.listen(model, 'after_update', make_listener('u'))
    event.listen(model, 'after_delete', make_listener('d'))
    return model

Example 9

Project: python-sync-db
Source File: tracking.py
View license
def _start_tracking(model, directions):
    if 'pull' in directions:
        core.pulled_models.add(model)
    if 'push' in directions:
        core.pushed_models.add(model)
    if model in core.synched_models.models:
        return model
    core.synched_models.install(model)
    event.listen(model, 'after_insert', make_listener('i'))
    event.listen(model, 'after_update', make_listener('u'))
    event.listen(model, 'after_delete', make_listener('d'))
    return model

Example 10

Project: sqlalchemy
Source File: listen_for_events.py
View license
def configure_listener(class_, key, inst):
    def append(instance, value, initiator):
        instance.receive_change_event("append", key, value, None)

    def remove(instance, value, initiator):
        instance.receive_change_event("remove", key, value, None)

    def set_(instance, value, oldvalue, initiator):
        instance.receive_change_event("set", key, value, oldvalue)

    event.listen(inst, 'append', append)
    event.listen(inst, 'remove', remove)
    event.listen(inst, 'set', set_)

Example 11

Project: sqlalchemy
Source File: test_events.py
View license
    def test_register_class(self):
        def listen(x, y):
            pass

        event.listen(self.Target, "event_one", listen)

        eq_(len(self.Target().dispatch.event_one), 1)
        eq_(len(self.Target().dispatch.event_two), 0)

Example 12

Project: sqlalchemy
Source File: test_events.py
View license
    def test_register_instance(self):
        def listen(x, y):
            pass

        t1 = self.Target()
        event.listen(t1, "event_one", listen)

        eq_(len(self.Target().dispatch.event_one), 0)
        eq_(len(t1.dispatch.event_one), 1)
        eq_(len(self.Target().dispatch.event_two), 0)
        eq_(len(t1.dispatch.event_two), 0)

Example 13

Project: sqlalchemy
Source File: test_events.py
View license
    def test_bool_clslevel(self):
        def listen_one(x, y):
            pass
        event.listen(self.Target, "event_one", listen_one)
        t = self.Target()
        assert t.dispatch.event_one

Example 14

Project: sqlalchemy
Source File: test_events.py
View license
    def test_append_vs_insert_cls(self):
        def listen_one(x, y):
            pass

        def listen_two(x, y):
            pass

        def listen_three(x, y):
            pass

        event.listen(self.Target, "event_one", listen_one)
        event.listen(self.Target, "event_one", listen_two)
        event.listen(self.Target, "event_one", listen_three, insert=True)

        eq_(
            list(self.Target().dispatch.event_one),
            [listen_three, listen_one, listen_two]
        )

Example 15

Project: sqlalchemy
Source File: test_events.py
View license
    def test_append_vs_insert_instance(self):
        def listen_one(x, y):
            pass

        def listen_two(x, y):
            pass

        def listen_three(x, y):
            pass

        target = self.Target()
        event.listen(target, "event_one", listen_one)
        event.listen(target, "event_one", listen_two)
        event.listen(target, "event_one", listen_three, insert=True)

        eq_(
            list(target.dispatch.event_one),
            [listen_three, listen_one, listen_two]
        )

Example 16

Project: sqlalchemy
Source File: test_events.py
View license
    def test_legacy_accept_partial(self):
        canary = Mock()

        def evt(a, x, y, **kw):
            canary(a, x, y, **kw)
        from functools import partial
        evt_partial = partial(evt, 5)
        target = self.TargetOne()
        event.listen(target, "event_four", evt_partial)
        # can't do legacy accept on a partial; we can't inspect it
        assert_raises(
            TypeError,
            target.dispatch.event_four, 4, 5, 6, 7, foo="bar"
        )
        target.dispatch.event_four(4, 5, foo="bar")
        eq_(
            canary.mock_calls,
            [call(5, 4, 5, foo="bar")]
        )

Example 17

Project: sqlalchemy
Source File: test_events.py
View license
    def test_legacy_accept_from_method(self):
        canary = Mock()

        class MyClass(object):
            def handler1(self, x, y):
                canary(x, y)

        event.listen(self.TargetOne, "event_three", MyClass().handler1)

        self.TargetOne().dispatch.event_three(4, 5, 6, 7)
        eq_(
            canary.mock_calls,
            [call(4, 5)]
        )

Example 18

Project: sqlalchemy
Source File: test_events.py
View license
    def test_standard_accept_has_legacies(self):
        canary = Mock()

        event.listen(self.TargetOne, "event_three", canary)

        self.TargetOne().dispatch.event_three(4, 5)

        eq_(
            canary.mock_calls,
            [call(4, 5)]
        )

Example 19

Project: sqlalchemy
Source File: test_events.py
View license
    def test_indirect(self):
        def listen(x, y):
            pass

        event.listen("one", "event_one", listen)

        eq_(
            list(self.Target().dispatch.event_one),
            [listen]
        )

        assert_raises(
            exc.InvalidRequestError,
            event.listen,
            listen, "event_one", self.Target
        )

Example 20

Project: sqlalchemy
Source File: test_events.py
View license
    def test_listen_override(self):
        listen_one = Mock()
        listen_two = Mock()

        event.listen(self.Target, "event_one", listen_one, add=True)
        event.listen(self.Target, "event_one", listen_two)

        t1 = self.Target()
        t1.dispatch.event_one(5, 7)
        t1.dispatch.event_one(10, 5)

        eq_(
            listen_one.mock_calls,
            [call(12), call(15)]
        )
        eq_(
            listen_two.mock_calls,
            [call(5, 7), call(10, 5)]
        )

Example 21

Project: sqlalchemy
Source File: test_events.py
View license
    def test_remove_clslevel(self):
        listen_one = Mock()
        event.listen(self.Target, "event_one", listen_one, add=True)
        t1 = self.Target()
        t1.dispatch.event_one(5, 7)
        eq_(
            listen_one.mock_calls,
            [call(12)]
        )
        event.remove(self.Target, "event_one", listen_one)
        t1.dispatch.event_one(10, 5)
        eq_(
            listen_one.mock_calls,
            [call(12)]
        )

Example 22

Project: sqlalchemy
Source File: test_events.py
View license
    def test_remove_instancelevel(self):
        listen_one = Mock()
        t1 = self.Target()
        event.listen(t1, "event_one", listen_one, add=True)
        t1.dispatch.event_one(5, 7)
        eq_(
            listen_one.mock_calls,
            [call(12)]
        )
        event.remove(t1, "event_one", listen_one)
        t1.dispatch.event_one(10, 5)
        eq_(
            listen_one.mock_calls,
            [call(12)]
        )

Example 23

Project: sqlalchemy
Source File: test_events.py
View license
    def test_kw_ok(self):
        l1 = Mock()

        def listen(**kw):
            l1(kw)

        event.listen(self.TargetFactory, "event_one", listen, named=True)
        element = self.TargetFactory().create()
        element.run_event(1)
        element.run_event(2)
        eq_(
            l1.mock_calls,
            [
                call({"target": element, "arg": 1}),
                call({"target": element, "arg": 2}),
            ]
        )

Example 24

Project: sqlalchemy
Source File: test_events.py
View license
    def test_parent_class_only(self):
        l1 = Mock()

        event.listen(self.TargetFactory, "event_one", l1)

        element = self.TargetFactory().create()
        element.run_event(1)
        element.run_event(2)
        element.run_event(3)
        eq_(
            l1.mock_calls,
            [call(element, 1), call(element, 2), call(element, 3)]
        )

Example 25

Project: sqlalchemy
Source File: test_events.py
View license
    def test_parent_class_child_class(self):
        l1 = Mock()
        l2 = Mock()

        event.listen(self.TargetFactory, "event_one", l1)
        event.listen(self.TargetElement, "event_one", l2)

        element = self.TargetFactory().create()
        element.run_event(1)
        element.run_event(2)
        element.run_event(3)
        eq_(
            l1.mock_calls,
            [call(element, 1), call(element, 2), call(element, 3)]
        )
        eq_(
            l2.mock_calls,
            [call(element, 1), call(element, 2), call(element, 3)]
        )

Example 26

Project: sqlalchemy
Source File: test_events.py
View license
    def test_parent_events_child_no_events(self):
        l1 = Mock()
        factory = self.TargetFactory()

        event.listen(self.TargetElement, "event_one", l1)
        element = factory.create()

        element.run_event(1)
        element.run_event(2)
        element.run_event(3)

        eq_(
            l1.mock_calls,
            [call(element, 1), call(element, 2), call(element, 3)]
        )

Example 27

Project: sqlalchemy
Source File: test_events.py
View license
    def test_clslevel(self):
        Target = self._fixture()

        m1 = Mock()

        event.listen(Target, "event_two", m1)

        t1 = Target()
        t1.dispatch.event_two("x")

        event.remove(Target, "event_two", m1)

        t1.dispatch.event_two("y")

        eq_(m1.mock_calls, [call("x")])

Example 28

Project: sqlalchemy
Source File: test_events.py
View license
    def test_clslevel_subclass(self):
        Target = self._fixture()

        class SubTarget(Target):
            pass

        m1 = Mock()

        event.listen(Target, "event_two", m1)

        t1 = SubTarget()
        t1.dispatch.event_two("x")

        event.remove(Target, "event_two", m1)

        t1.dispatch.event_two("y")

        eq_(m1.mock_calls, [call("x")])

Example 29

Project: sqlalchemy
Source File: test_events.py
View license
    def test_remove_not_listened(self):
        Target = self._fixture()

        m1 = Mock()

        t1 = Target()

        event.listen(t1, "event_one", m1, propagate=True)
        event.listen(t1, "event_three", m1)

        event.remove(t1, "event_one", m1)
        assert_raises_message(
            exc.InvalidRequestError,
            r"No listeners found for event <.*Target.*> / "
            r"'event_two' / <Mock.*> ",
            event.remove, t1, "event_two", m1
        )

        event.remove(t1, "event_three", m1)

Example 30

Project: sqlalchemy
Source File: test_events.py
View license
    def test_no_add_in_event(self):
        Target = self._fixture()

        t1 = Target()

        m1 = Mock()

        def evt():
            event.listen(t1, "event_one", m1)

        event.listen(t1, "event_one", evt)

        assert_raises_message(
            Exception,
            "deque mutated during iteration",
            t1.dispatch.event_one
        )

Example 31

Project: sqlalchemy
Source File: test_events.py
View license
    def test_remove_plain_named(self):
        Target = self._fixture()

        listen_one = Mock()
        t1 = Target()
        event.listen(t1, "event_one", listen_one, named=True)
        t1.dispatch.event_one("t1")

        eq_(listen_one.mock_calls, [call(x="t1")])
        event.remove(t1, "event_one", listen_one)
        t1.dispatch.event_one("t2")

        eq_(listen_one.mock_calls, [call(x="t1")])

Example 32

Project: sqlalchemy
Source File: test_events.py
View license
    def test_remove_wrapped_named(self):
        Target = self._wrapped_fixture()

        listen_one = Mock()
        t1 = Target()
        event.listen(t1, "event_one", listen_one, named=True)
        t1.dispatch.event_one("t1")

        eq_(listen_one.mock_calls, [call(x="adapted t1")])
        event.remove(t1, "event_one", listen_one)
        t1.dispatch.event_one("t2")

        eq_(listen_one.mock_calls, [call(x="adapted t1")])

Example 33

Project: sqlalchemy
Source File: test_events.py
View license
    def test_double_event_nonwrapped(self):
        Target = self._fixture()

        listen_one = Mock()
        t1 = Target()
        event.listen(t1, "event_one", listen_one)
        event.listen(t1, "event_one", listen_one)

        t1.dispatch.event_one("t1")

        # doubles are eliminated
        eq_(listen_one.mock_calls, [call("t1")])

        # only one remove needed
        event.remove(t1, "event_one", listen_one)
        t1.dispatch.event_one("t2")

        eq_(listen_one.mock_calls, [call("t1")])

Example 34

Project: sqlalchemy
Source File: test_ddlevents.py
View license
    def test_table_create_before(self):
        table, bind = self.table, self.bind
        canary = mock.Mock()
        event.listen(table, 'before_create', canary.before_create)

        table.create(bind)
        table.drop(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.before_create(
                    table, self.bind, checkfirst=False,
                    _ddl_runner=mock.ANY, _is_metadata_operation=mock.ANY)
            ]
        )

Example 35

Project: sqlalchemy
Source File: test_ddlevents.py
View license
    def test_table_create_after(self):
        table, bind = self.table, self.bind
        canary = mock.Mock()
        event.listen(table, 'after_create', canary.after_create)

        table.create(bind)
        table.drop(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.after_create(
                    table, self.bind, checkfirst=False,
                    _ddl_runner=mock.ANY, _is_metadata_operation=mock.ANY)
            ]
        )

Example 36

Project: sqlalchemy
Source File: test_ddlevents.py
View license
    def test_table_create_both(self):
        table, bind = self.table, self.bind
        canary = mock.Mock()
        event.listen(table, 'before_create', canary.before_create)
        event.listen(table, 'after_create', canary.after_create)

        table.create(bind)
        table.drop(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.before_create(
                    table, self.bind, checkfirst=False,
                    _ddl_runner=mock.ANY, _is_metadata_operation=mock.ANY),
                mock.call.after_create(
                    table, self.bind, checkfirst=False,
                    _ddl_runner=mock.ANY, _is_metadata_operation=mock.ANY)
            ]
        )

Example 37

Project: sqlalchemy
Source File: test_ddlevents.py
View license
    def test_table_drop_before(self):
        table, bind = self.table, self.bind
        canary = mock.Mock()
        event.listen(table, 'before_drop', canary.before_drop)

        table.create(bind)
        table.drop(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.before_drop(
                    table, self.bind, checkfirst=False,
                    _ddl_runner=mock.ANY, _is_metadata_operation=mock.ANY),
            ]
        )

Example 38

Project: sqlalchemy
Source File: test_ddlevents.py
View license
    def test_table_drop_after(self):
        table, bind = self.table, self.bind
        canary = mock.Mock()
        event.listen(table, 'after_drop', canary.after_drop)

        table.create(bind)
        canary.state = 'skipped'
        table.drop(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.after_drop(
                    table, self.bind, checkfirst=False,
                    _ddl_runner=mock.ANY, _is_metadata_operation=mock.ANY),
            ]
        )

Example 39

Project: sqlalchemy
Source File: test_ddlevents.py
View license
    def test_metadata_create_before(self):
        metadata, bind = self.metadata, self.bind
        canary = mock.Mock()
        event.listen(metadata, 'before_create', canary.before_create)

        metadata.create_all(bind)
        metadata.drop_all(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.before_create(
                    # checkfirst is False because of the MockConnection
                    # used in the current testing strategy.
                    metadata, self.bind, checkfirst=False,
                    tables=list(metadata.tables.values()),
                    _ddl_runner=mock.ANY),
            ]
        )

Example 40

Project: sqlalchemy
Source File: test_ddlevents.py
View license
    def test_metadata_create_after(self):
        metadata, bind = self.metadata, self.bind
        canary = mock.Mock()
        event.listen(metadata, 'after_create', canary.after_create)

        metadata.create_all(bind)
        metadata.drop_all(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.after_create(
                    metadata, self.bind, checkfirst=False,
                    tables=list(metadata.tables.values()),
                    _ddl_runner=mock.ANY),
            ]
        )

Example 41

Project: sqlalchemy
Source File: test_ddlevents.py
View license
    def test_metadata_drop_before(self):
        metadata, bind = self.metadata, self.bind
        canary = mock.Mock()
        event.listen(metadata, 'before_drop', canary.before_drop)

        metadata.create_all(bind)
        metadata.drop_all(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.before_drop(
                    metadata, self.bind, checkfirst=False,
                    tables=list(metadata.tables.values()),
                    _ddl_runner=mock.ANY),
            ]
        )

Example 42

Project: sqlalchemy
Source File: test_ddlevents.py
View license
    def test_metadata_drop_after(self):
        metadata, bind = self.metadata, self.bind
        canary = mock.Mock()
        event.listen(metadata, 'after_drop', canary.after_drop)

        metadata.create_all(bind)
        metadata.drop_all(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.after_drop(
                    metadata, self.bind, checkfirst=False,
                    tables=list(metadata.tables.values()),
                    _ddl_runner=mock.ANY),
            ]
        )

Example 43

Project: sqlalchemy
Source File: test_horizontal_shard.py
View license
    def test_shard_id_event(self):
        canary = []
        def load(instance, ctx):
            canary.append(ctx.attributes["shard_id"])

        event.listen(WeatherLocation, "load", load)
        sess = self._fixture_data()

        tokyo = sess.query(WeatherLocation).\
                    filter_by(city="Tokyo").set_shard("asia").one()

        sess.query(WeatherLocation).all()
        eq_(
            canary,
            ['asia', 'north_america', 'north_america',
            'europe', 'europe', 'south_america',
            'south_america']
        )

Example 44

Project: sqlalchemy
Source File: test_instrumentation.py
View license
    def register(self, cls, canary):
        original_init = cls.__init__
        instrumentation.register_class(cls)
        ne_(cls.__init__, original_init)
        manager = instrumentation.manager_of_class(cls)
        def init(state, args, kwargs):
            canary.append((cls, 'init', state.class_))
        event.listen(manager, 'init', init, raw=True)

Example 45

Project: sqlalchemy
Source File: test_instrumentation.py
View license
    def _instrument(self, cls):
        manager = instrumentation.register_class(cls)
        canary = []
        def check(target, args, kwargs):
            canary.append((args, kwargs))
        event.listen(manager, "init", check)
        return cls, canary

Example 46

Project: flask-whooshee
Source File: flask_whooshee.py
View license
    def register_whoosheer(self, wh):
        """This will register the given whoosher on `whoosheers`, create the
        neccessary SQLAlchemy event listeners, replace the `query_class` with
        our own query class which will provide the search functionality
        and store the app on the whoosheer, so that we can always work
        with that.

        :param wh: The whoosher which should be registered.
        """
        self.whoosheers.append(wh)
        for model in wh.models:
            event.listen(model, 'after_{0}'.format(INSERT_KWD), self.after_insert)
            event.listen(model, 'after_{0}'.format(UPDATE_KWD), self.after_update)
            event.listen(model, 'after_{0}'.format(DELETE_KWD), self.after_delete)
            model.query_class = self.query
        if self.app:
            wh.app = self.app
        return wh

Example 47

Project: odo
Source File: sql.py
View license
def attach_schema(obj, schema):
    if schema is not None:
        ddl = CreateSchema(schema, quote=True)
        event.listen(
            obj,
            'before_create',
            ddl.execute_if(
                callable_=should_create_schema,
                dialect='postgresql'
            )
        )
    return obj

Example 48

Project: sqlalchemy_exasol
Source File: base.py
View license
    def create_table_constraints(self, table, _include_foreign_key_constraints=None):
        # EXASOL does not support FK constraints that reference
        # the table being created. Thus, these need to be created
        # via ALTER TABLE after table creation
        # TODO: FKs that reference other tables could be inlined
        # the create rule could be more specific but for now, ALTER
        # TABLE for all FKs work.
        for c in [c for c in table._sorted_constraints if isinstance(c, ForeignKeyConstraint)]:
            c._create_rule = lambda: False
            event.listen(table, "after_create", AddConstraint(c))
        return super(EXADDLCompiler, self).create_table_constraints(table)

Example 49

Project: box-python-sdk
Source File: event_behavior.py
View license
    def __init__(self, db_session):
        self._db_session = db_session
        self._subscribe_event = Event()
        self._epoch = datetime.utcnow()

        def handle_event(*_):
            self._subscribe_event.set()

        event.listen(EventModel, 'after_insert', handle_event)

Example 50

Project: bodhi
Source File: base.py
View license
    def setUp(self):
        engine = create_engine(DB_PATH)
        # We want a special session that lasts longer than a transaction
        Session = scoped_session(
            sessionmaker(bind=engine, extension=ZopeTransactionExtension(keep_session=True)))
        log.debug('Creating all models for %s' % engine)
        Base.metadata.bind = engine
        Base.metadata.create_all(engine)
        self.db = Session()
        populate(self.db)

        # Track sql statements in every test
        self.sql_statements = []

        def track(conn, cursor, statement, param, ctx, many):
            self.sql_statements.append(statement)

        event.listen(engine, "before_cursor_execute", track)