Python sqlalchemy.event.remove() Examples

The following are 30 code examples of sqlalchemy.event.remove(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.event , or try the search function .
Example #1
Source File: test_events.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_instance(self):
        Target = self._fixture()

        class Foo(object):
            def __init__(self):
                self.mock = Mock()

            def evt(self, arg):
                self.mock(arg)

        f1 = Foo()
        f2 = Foo()

        event.listen(Target, "event_one", f1.evt)
        event.listen(Target, "event_one", f2.evt)

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

        event.remove(Target, "event_one", f1.evt)

        t1.dispatch.event_one("y")

        eq_(f1.mock.mock_calls, [call("x")])
        eq_(f2.mock.mock_calls, [call("x"), call("y")]) 
Example #2
Source File: registry.py    From AnyBlok with Mozilla Public License 2.0 6 votes vote down vote up
def precommit_hook(self, registryname, method, *args, **kwargs):
        """ Add a method in the precommit_hook list

        a precommit hook is a method called just before the commit, it is used
        to call this method once, because a hook is saved only once

        :param registryname: namespace of the model
        :param method: method to call on the registryname
        :param put_at_the_end_if_exist: if true and hook allready exist then the
            hook are moved at the end
        """
        put_at_the_end_if_exist = kwargs.pop('put_at_the_end_if_exist', False)

        entry = (registryname, method, args, kwargs)
        _precommit_hook = EnvironmentManager.get('_precommit_hook', [])
        if entry in _precommit_hook:
            if put_at_the_end_if_exist:
                _precommit_hook.remove(entry)
                _precommit_hook.append(entry)

        else:
            _precommit_hook.append(entry)

        EnvironmentManager.set('_precommit_hook', _precommit_hook) 
Example #3
Source File: registry.py    From AnyBlok with Mozilla Public License 2.0 6 votes vote down vote up
def apply_postcommit_hook(self, withexception=False):
        hooks = []
        _postcommit_hook = EnvironmentManager.get('_postcommit_hook')
        if _postcommit_hook:
            hooks.extend(_postcommit_hook)

        for hook in hooks:
            registryname, method, call_only_if, a, kw = hook
            if withexception is False and call_only_if == 'raised':
                _postcommit_hook.remove(hook)
                continue

            if withexception is True and call_only_if == 'commited':
                _postcommit_hook.remove(hook)
                continue

            Model = self.loaded_namespaces[registryname]
            try:
                getattr(Model, method)(*a, **kw)
            except Exception as e:
                logger.exception(str(e))
            finally:
                _postcommit_hook.remove(hook) 
Example #4
Source File: test_baked.py    From sqlalchemy with MIT License 6 votes vote down vote up
def modify_query_fixture(self):
        def set_event(bake_ok):

            event.listen(
                Query,
                "before_compile",
                _modify_query,
                retval=True,
                bake_ok=bake_ok,
            )
            return m1

        m1 = mock.Mock()

        def _modify_query(query):
            m1(query.column_descriptions[0]["entity"])
            query = query.enable_assertions(False).filter(
                literal_column("1") == 1
            )
            return query

        yield set_event
        event.remove(Query, "before_compile", _modify_query) 
Example #5
Source File: test_events.py    From sqlalchemy with MIT License 6 votes vote down vote up
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 #6
Source File: testing.py    From AnyBlok with Mozilla Public License 2.0 6 votes vote down vote up
def drop_database(url):
    url = copy(sqlalchemy.engine.url.make_url(url))
    database = url.database
    if url.drivername.startswith('postgresql'):
        url.database = 'postgres'
    elif not url.drivername.startswith('sqlite'):
        url.database = None

    engine = sqlalchemy.create_engine(url)
    if engine.dialect.name == 'sqlite' and url.database != ':memory:':
        os.remove(url.database)
    else:
        text = 'DROP DATABASE {0}'.format(orm.quote(engine, database))
        cnx = engine.connect()
        cnx.execute("ROLLBACK")
        cnx.execute(text)
        cnx.execute("commit")
        cnx.close() 
Example #7
Source File: test_events.py    From sqlalchemy with MIT License 6 votes vote down vote up
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 #8
Source File: base.py    From ctfscoreboard with Apache License 2.0 6 votes vote down vote up
def __exit__(self, exc_type, exc_value, exc_traceback):
        event.remove(*self._sql_listen_args)
        if exc_type is not None:
            return False
        if self.test_id:
            limit_msg = ((' Limit: %d.' % self.max_count)
                         if self.max_count is not None else '')
            logging.info('%s executed %d queries.%s',
                         self.test_id, len(self.queries), limit_msg)
        if self.max_count is None:
            return
        if len(self.queries) > self.max_count:
            message = ('Maximum query count exceeded: limit %d, executed %d.\n'
                       '----QUERIES----\n%s\n----END----') % (
                            self.max_count,
                            len(self.queries),
                            '\n'.join(self.queries))
            raise AssertionError(message) 
Example #9
Source File: test_events.py    From sqlalchemy with MIT License 6 votes vote down vote up
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 #10
Source File: test_events.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_double_event_wrapped(self):
        # this is issue #3199
        Target = self._wrapped_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("adapted t1")])

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

        eq_(listen_one.mock_calls, [call("adapted t1")]) 
Example #11
Source File: test_events.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_instance_event_listen_on_cls_before_map(self):
        users = self.tables.users

        fn = Mock()

        class User(object):
            pass

        event.listen(User, "load", fn)
        m = mapper(User, users)

        u1 = User()
        m.class_manager.dispatch.load(u1._sa_instance_state, "u1")

        event.remove(User, "load", fn)

        m.class_manager.dispatch.load(u1._sa_instance_state, "u2")

        eq_(fn.mock_calls, [call(u1, "u1")]) 
Example #12
Source File: fixtures.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def teardown(self):
        for key in self._event_fns:
            event.remove(*key)
        super_ = super(RemovesEvents, self)
        if hasattr(super_, "teardown"):
            super_.teardown() 
Example #13
Source File: fixtures.py    From planespotter with MIT License 5 votes vote down vote up
def teardown(self):
        for key in self._event_fns:
            event.remove(*key)
        super_ = super(RemovesEvents, self)
        if hasattr(super_, "teardown"):
            super_.teardown() 
Example #14
Source File: test_events.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_immutable_methods(self):
        t1 = self.Target()
        for meth in [
            t1.dispatch.event_one.exec_once,
            t1.dispatch.event_one.insert,
            t1.dispatch.event_one.append,
            t1.dispatch.event_one.remove,
            t1.dispatch.event_one.clear,
        ]:
            assert_raises_message(
                NotImplementedError, r"need to call for_modify\(\)", meth
            ) 
Example #15
Source File: __init__.py    From planespotter with MIT License 5 votes vote down vote up
def unregister(cls, session):
        if hasattr(session, '_model_changes'):
            del session._model_changes

        event.remove(session, 'before_flush', cls.record_ops)
        event.remove(session, 'before_commit', cls.record_ops)
        event.remove(session, 'before_commit', cls.before_commit)
        event.remove(session, 'after_commit', cls.after_commit)
        event.remove(session, 'after_rollback', cls.after_rollback) 
Example #16
Source File: fixtures.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def teardown(self):
        for key in self._event_fns:
            event.remove(*key)
        super_ = super(RemovesEvents, self)
        if hasattr(super_, "teardown"):
            super_.teardown() 
Example #17
Source File: api.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def remove(target, identifier, fn):
    """Remove an event listener.

    The arguments here should match exactly those which were sent to
    :func:`.listen`; all the event registration which proceeded as a result
    of this call will be reverted by calling :func:`.remove` with the same
    arguments.

    e.g.::

        # if a function was registered like this...
        @event.listens_for(SomeMappedClass, "before_insert", propagate=True)
        def my_listener_function(*arg):
            pass

        # ... it's removed like this
        event.remove(SomeMappedClass, "before_insert", my_listener_function)

    Above, the listener function associated with ``SomeMappedClass`` was also
    propagated to subclasses of ``SomeMappedClass``; the :func:`.remove`
    function will revert all of these operations.

    .. versionadded:: 0.9.0

    """
    _event_key(target, identifier, fn).remove() 
Example #18
Source File: fixtures.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def teardown(self):
        for key in self._event_fns:
            event.remove(*key)
        super_ = super(RemovesEvents, self)
        if hasattr(super_, "teardown"):
            super_.teardown() 
Example #19
Source File: sqlalchemy.py    From airflow with Apache License 2.0 5 votes vote down vote up
def __exit__(self, type_, value, traceback):
        import airflow.settings

        event.remove(airflow.settings.engine, "after_cursor_execute", self.after_cursor_execute)
        self.print_fn(f"Count SQL queries: {self.result.count}") 
Example #20
Source File: test_models.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def test_soft_delete_coerce_deleted_to_integer(self):
        def listener(conn, cur, stmt, params, context, executemany):
            if 'insert' in stmt.lower():  # ignore SELECT 1 and BEGIN
                self.assertNotIn('False', str(params))

        event.listen(self.engine, 'before_cursor_execute', listener)
        self.addCleanup(event.remove,
                        self.engine, 'before_cursor_execute', listener)

        m = SoftDeletedModel(id=1, smth='test', deleted=False)
        self.session.add(m)
        self.session.commit() 
Example #21
Source File: sqlalchemy.py    From opentracing-python-instrumentation with MIT License 5 votes vote down vote up
def _reset_patches(self):
        event.remove(Engine, 'before_cursor_execute',
                     self.before_cursor_execute)
        event.remove(Engine, 'after_cursor_execute',
                     self.after_cursor_execute) 
Example #22
Source File: test_baked.py    From sqlalchemy with MIT License 5 votes vote down vote up
def before_compile_nobake_fixture(self):
        @event.listens_for(Query, "before_compile", retval=True)
        def _modify_query(query):
            query = query.enable_assertions(False)
            return query

        yield
        event.remove(Query, "before_compile", _modify_query) 
Example #23
Source File: test_events.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_unmapped_listen(self):
        users = self.tables.users

        class Foo(object):
            pass

        fn = Mock()

        event.listen(Foo, "before_insert", fn, propagate=True)

        class User(Foo):
            pass

        m = mapper(User, users)

        u1 = User()
        m.dispatch.before_insert(m, None, attributes.instance_state(u1))
        eq_(fn.call_count, 1)

        event.remove(Foo, "before_insert", fn)

        # existing event is removed
        m.dispatch.before_insert(m, None, attributes.instance_state(u1))
        eq_(fn.call_count, 1)

        # the _HoldEvents is also cleaned out
        class Bar(Foo):
            pass

        m = mapper(Bar, users)
        b1 = Bar()
        m.dispatch.before_insert(m, None, attributes.instance_state(b1))
        eq_(fn.call_count, 1) 
Example #24
Source File: test_events.py    From sqlalchemy with MIT License 5 votes vote down vote up
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 #25
Source File: test_events.py    From sqlalchemy with MIT License 5 votes vote down vote up
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 #26
Source File: test_events.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_remove_invoke_clslevel(self):
        canary = Mock()

        event.listen(self.BaseTarget, "event_one", canary)

        s1 = self.SubTarget(self.BaseTarget())

        event.remove(self.BaseTarget, "event_one", canary)

        s1.dispatch.event_one()

        eq_(canary.mock_calls, []) 
Example #27
Source File: test_events.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_propagate(self):
        Target = self._fixture()

        m1 = Mock()

        t1 = Target()
        t2 = Target()

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

        t2.dispatch._update(t1.dispatch)

        t1.dispatch.event_one("t1e1x")
        t1.dispatch.event_two("t1e2x")
        t2.dispatch.event_one("t2e1x")
        t2.dispatch.event_two("t2e2x")

        event.remove(t1, "event_one", m1)
        event.remove(t1, "event_two", m1)

        t1.dispatch.event_one("t1e1y")
        t1.dispatch.event_two("t1e2y")
        t2.dispatch.event_one("t2e1y")
        t2.dispatch.event_two("t2e2y")

        eq_(m1.mock_calls, [call("t1e1x"), call("t1e2x"), call("t2e1x")]) 
Example #28
Source File: test_events.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_no_remove_in_event(self):
        Target = self._fixture()

        t1 = Target()

        def evt():
            event.remove(t1, "event_one", evt)

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

        assert_raises_message(
            Exception, "deque mutated during iteration", t1.dispatch.event_one
        ) 
Example #29
Source File: test_events.py    From sqlalchemy with MIT License 5 votes vote down vote up
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 #30
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_event_no_native_float(self):
        def _remove_type(inputsizes, cursor, statement, parameters, context):
            for param, dbapitype in list(inputsizes.items()):
                if dbapitype is testing.db.dialect.dbapi.NATIVE_FLOAT:
                    del inputsizes[param]

        event.listen(testing.db, "do_setinputsizes", _remove_type)
        try:
            self.test_setinputsizes(oracle.BINARY_FLOAT, 25.34534, None, False)
        finally:
            event.remove(testing.db, "do_setinputsizes", _remove_type)