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.
392 Examples
3
Source : events.py
with MIT License
from 3lpsy
with MIT License
from 3lpsy
def db_register_model_events(models):
for m in models:
for event_name in ORM_EVENTS:
event_cb = "on_" + event_name
if hasattr(m, event_cb):
logger.info(
"[email protected]: registering "
+ event_cb
+ " on "
+ str(m)
)
listen(m, event_name, make_event(getattr(m, event_cb)))
def db_register_search_events(session, mixin):
3
Source : batch.py
with GNU Affero General Public License v3.0
from andrewcooke
with GNU Affero General Public License v3.0
from andrewcooke
def enable(self, session):
if self.enabled:
if session not in self.__sessions:
self.__sessions.add(session)
self.sessions += 1
listen(session, 'before_flush', self.__before_flush)
else:
log.warning(f'Tried to register session more than once')
def __before_flush(self, session, context, instances):
3
Source : triggers.py
with GNU Affero General Public License v3.0
from andrewcooke
with GNU Affero General Public License v3.0
from andrewcooke
def add_child_ddl(parent_table):
parent = parent_table.__tablename__
def decorator(child_table):
child = child_table.__tablename__
identity = child_table.__mapper_args__['polymorphic_identity']
listen(child_table.__table__, 'after_create',
child_ddl(parent, child, identity).
execute_if(dialect='postgresql'))
return child_table
return decorator
def add_text(ddl):
3
Source : triggers.py
with GNU Affero General Public License v3.0
from andrewcooke
with GNU Affero General Public License v3.0
from andrewcooke
def add_text(ddl):
def decorator(table_cls):
listen(table_cls.__table__, 'after_create', DDL(ddl).execute_if(dialect='postgresql'))
return table_cls
return decorator
3
Source : __init__.py
with MIT License
from dhina016
with MIT License
from dhina016
def register(cls, session):
if not hasattr(session, '_model_changes'):
session._model_changes = {}
event.listen(session, 'before_flush', cls.record_ops)
event.listen(session, 'before_commit', cls.record_ops)
event.listen(session, 'before_commit', cls.before_commit)
event.listen(session, 'after_commit', cls.after_commit)
event.listen(session, 'after_rollback', cls.after_rollback)
@classmethod
3
Source : __init__.py
with MIT License
from dhina016
with MIT License
from dhina016
def register(self):
event.listen(
self.engine, 'before_cursor_execute', self.before_cursor_execute
)
event.listen(
self.engine, 'after_cursor_execute', self.after_cursor_execute
)
def before_cursor_execute(
3
Source : aws_rds_iam_support.py
with MIT License
from dialoguemd
with MIT License
from dialoguemd
def setup(engine):
config = Config()
if config.aws_rds_iam_enabled:
assert boto3_installed, boto3_installed_err
event.listen(engine, "do_connect", set_connection_token)
def get_authentication_token(host, port, user):
3
Source : profiler.py
with MIT License
from dmvass
with MIT License
from dmvass
def begin(self):
"""Begin profiling session.
:raises AssertionError: When the session is already alive.
"""
if self.alive:
raise AssertionError("Profiling session has already begun")
self.alive = True
self.queries = Queue()
self._reset_stats()
event.listen(self.engine, self._before, self._before_cursor_execute)
event.listen(self.engine, self._after, self._after_cursor_execute)
def commit(self):
3
Source : snippet.py
with Apache License 2.0
from dockerizeme
with Apache License 2.0
from dockerizeme
def register_events(self):
for dependency in self._dependencies():
event.listen(
dependency,
'after_create',
self.create_after_all_dependencies
)
event.listen(
dependency,
"before_drop",
self.drop_before_all_dependencies
)
def _dependencies(self):
3
Source : db.py
with GNU Affero General Public License v3.0
from eReuse
with GNU Affero General Public License v3.0
from eReuse
def create_view(name, selectable):
"""Creates a view.
This is an adaptation from sqlalchemy_utils.view. See
`the test on sqlalchemy-utils < https://github.com/kvesteri/
sqlalchemy-utils/blob/master/tests/test_views.py>`_ for an
example on how to use.
"""
table = view.create_table_from_selectable(name, selectable)
# We need to ensure views are created / destroyed before / after
# SchemaSQLAlchemy's listeners execute
# That is why insert=True in 'after_create'
event.listen(db.metadata, 'after_create', view.CreateView(name, selectable), insert=True)
event.listen(db.metadata, 'before_drop', view.DropView(name))
return table
db = SQLAlchemy(session_options={'autoflush': False})
3
Source : listen_for_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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_)
if __name__ == "__main__":
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)
def test_register_instance(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)
def test_bool_clslevel(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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
def test_register_class_instance(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_exec_once(self):
m1 = Mock()
event.listen(self.Target, "event_one", m1)
t1 = self.Target()
t2 = self.Target()
t1.dispatch.event_one.for_modify(t1.dispatch).exec_once(5, 6)
t1.dispatch.event_one.for_modify(t1.dispatch).exec_once(7, 8)
t2.dispatch.event_one.for_modify(t2.dispatch).exec_once(9, 10)
eq_(m1.mock_calls, [call(5, 6), call(9, 10)])
def test_exec_once_exception(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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")])
def _test_legacy_accept_kw(self, target, canary):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)])
def test_standard_accept_has_legacies(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)])
def test_kw_accept_has_legacies(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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,
)
class SubclassGrowthTest(fixtures.TestBase):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)])
def test_remove_clslevel(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)])
def test_remove_instancelevel(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)])
class PropagateTest(fixtures.TestBase):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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}),
],
)
def test_parent_class_only(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)],
)
def test_parent_class_child_class(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)],
)
class DisableClsPropagateTest(fixtures.TestBase):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_listen_invoke_clslevel(self):
canary = Mock()
event.listen(self.BaseTarget, "event_one", canary)
s1 = self.SubTarget(self.BaseTarget())
s1.dispatch.event_one()
eq_(canary.mock_calls, [call.event_one()])
def test_insert_invoke_clslevel(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_insert_invoke_clslevel(self):
canary = Mock()
event.listen(self.BaseTarget, "event_one", canary, insert=True)
s1 = self.SubTarget(self.BaseTarget())
s1.dispatch.event_one()
eq_(canary.mock_calls, [call.event_one()])
def test_remove_invoke_clslevel(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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, [])
class RemovalTest(fixtures.TestBase):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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")])
def test_clslevel_subclass(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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
)
def test_remove_plain_named(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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")])
def test_remove_wrapped_named(self):
3
Source : test_events.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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")])
def test_double_event_nonwrapped(self):
3
Source : test_types.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)
3
Source : test_deprecations.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_legacy_dbapi_error(self):
engine = engines.testing_engine()
canary = Mock()
with testing.expect_deprecated(
r"The ConnectionEvents.dbapi_error\(\) event is deprecated"
):
event.listen(engine, "dbapi_error", canary)
with engine.connect() as conn:
try:
conn.execute("SELECT FOO FROM I_DONT_EXIST")
assert False
except tsa.exc.DBAPIError as e:
eq_(canary.mock_calls[0][1][5], e.orig)
eq_(canary.mock_calls[0][1][2], "SELECT FOO FROM I_DONT_EXIST")
def test_legacy_dbapi_error_no_ad_hoc_context(self):
3
Source : test_execute.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_generative_engine_event_dispatch_hasevents(self):
def l1(*arg, **kw):
pass
eng = create_engine(testing.db.url)
assert not eng._has_events
event.listen(eng, "before_execute", l1)
eng2 = eng.execution_options(foo="bar")
assert eng2._has_events
def test_unicode_test_fails_warning(self):
3
Source : test_execute.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_per_engine_independence(self):
e1 = testing_engine(config.db_url)
e2 = testing_engine(config.db_url)
canary = Mock()
event.listen(e1, "before_execute", canary)
s1 = select([1])
s2 = select([2])
e1.execute(s1)
e2.execute(s2)
eq_([arg[1][1] for arg in canary.mock_calls], [s1])
event.listen(e2, "before_execute", canary)
e1.execute(s1)
e2.execute(s2)
eq_([arg[1][1] for arg in canary.mock_calls], [s1, s1, s2])
def test_per_engine_plus_global(self):
3
Source : test_execute.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_per_connection_plus_engine(self):
canary = Mock()
e1 = testing_engine(config.db_url)
event.listen(e1, "before_execute", canary.be1)
conn = e1.connect()
event.listen(conn, "before_execute", canary.be2)
conn.execute(select([1]))
eq_(canary.be1.call_count, 1)
eq_(canary.be2.call_count, 1)
conn._branch().execute(select([1]))
eq_(canary.be1.call_count, 2)
eq_(canary.be2.call_count, 2)
def test_add_event_after_connect(self):
3
Source : test_execute.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_add_event_after_connect(self):
# new feature as of #2978
canary = Mock()
e1 = create_engine(config.db_url)
assert not e1._has_events
conn = e1.connect()
event.listen(e1, "before_execute", canary.be1)
conn.execute(select([1]))
eq_(canary.be1.call_count, 1)
conn._branch().execute(select([1]))
eq_(canary.be1.call_count, 2)
def test_force_conn_events_false(self):
3
Source : test_execute.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_force_conn_events_false(self):
canary = Mock()
e1 = create_engine(config.db_url)
assert not e1._has_events
event.listen(e1, "before_execute", canary.be1)
conn = e1._connection_cls(
e1, connection=e1.raw_connection(), _has_events=False
)
conn.execute(select([1]))
eq_(canary.be1.call_count, 0)
conn._branch().execute(select([1]))
eq_(canary.be1.call_count, 0)
def test_cursor_events_ctx_execute_scalar(self):
3
Source : test_execute.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_argument_format_execute(self):
def before_execute(conn, clauseelement, multiparams, params):
assert isinstance(multiparams, (list, tuple))
assert isinstance(params, dict)
def after_execute(conn, clauseelement, multiparams, params, result):
assert isinstance(multiparams, (list, tuple))
assert isinstance(params, dict)
e1 = testing_engine(config.db_url)
event.listen(e1, "before_execute", before_execute)
event.listen(e1, "after_execute", after_execute)
e1.execute(select([1]))
e1.execute(select([1]).compile(dialect=e1.dialect).statement)
e1.execute(select([1]).compile(dialect=e1.dialect))
e1._execute_compiled(select([1]).compile(dialect=e1.dialect), (), {})
@testing.fails_on("firebird", "Data type unknown")
3
Source : test_execute.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_cant_listen_to_option_engine(self):
from sqlalchemy.engine import base
def evt(*arg, **kw):
pass
assert_raises_message(
tsa.exc.InvalidRequestError,
r"Can't assign an event directly to the "
" < class 'sqlalchemy.engine.base.OptionEngine'> class",
event.listen,
base.OptionEngine,
"before_cursor_execute",
evt,
)
@testing.requires.ad_hoc_engines
3
Source : test_execute.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_dispose_event(self):
canary = Mock()
eng = create_engine(testing.db.url)
event.listen(eng, "engine_disposed", canary)
conn = eng.connect()
conn.close()
eng.dispose()
conn = eng.connect()
conn.close()
eq_(canary.mock_calls, [call(eng)])
eng.dispose()
eq_(canary.mock_calls, [call(eng), call(eng)])
def test_retval_flag(self):
3
Source : test_execute.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_engine_connect(self):
engine = engines.testing_engine()
tracker = Mock()
event.listen(engine, "engine_connect", tracker)
c1 = engine.connect()
c2 = c1._branch()
c1.close()
eq_(tracker.mock_calls, [call(c1, False), call(c2, True)])
def test_execution_options(self):
3
Source : test_execute.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_handle_error(self):
engine = engines.testing_engine()
canary = Mock(return_value=None)
event.listen(engine, "handle_error", canary)
with engine.connect() as conn:
try:
conn.execute("SELECT FOO FROM I_DONT_EXIST")
assert False
except tsa.exc.DBAPIError as e:
ctx = canary.mock_calls[0][1][0]
eq_(ctx.original_exception, e.orig)
is_(ctx.sqlalchemy_exception, e)
eq_(ctx.statement, "SELECT FOO FROM I_DONT_EXIST")
def test_exception_event_reraise(self):
3
Source : test_pool.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def _first_connect_event_fixture(self):
p = self._queuepool_fixture()
canary = []
def first_connect(*arg, **kw):
canary.append("first_connect")
event.listen(p, "first_connect", first_connect)
return p, canary
def _connect_event_fixture(self):
3
Source : test_pool.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def _connect_event_fixture(self):
p = self._queuepool_fixture()
canary = []
def connect(*arg, **kw):
canary.append("connect")
event.listen(p, "connect", connect)
return p, canary
def _checkout_event_fixture(self):
3
Source : test_pool.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def _checkout_event_fixture(self):
p = self._queuepool_fixture()
canary = []
def checkout(*arg, **kw):
canary.append("checkout")
event.listen(p, "checkout", checkout)
return p, canary
def _checkin_event_fixture(self):
3
Source : test_pool.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def _checkin_event_fixture(self):
p = self._queuepool_fixture()
canary = []
def checkin(*arg, **kw):
canary.append("checkin")
event.listen(p, "checkin", checkin)
return p, canary
def _reset_event_fixture(self):
3
Source : test_pool.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def _reset_event_fixture(self):
p = self._queuepool_fixture()
canary = []
def reset(*arg, **kw):
canary.append("reset")
event.listen(p, "reset", reset)
return p, canary
def _invalidate_event_fixture(self):
3
Source : test_pool.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def _invalidate_event_fixture(self):
p = self._queuepool_fixture()
canary = Mock()
event.listen(p, "invalidate", canary)
return p, canary
def _soft_invalidate_event_fixture(self):
See More Examples