sqlalchemy.event.listens_for

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

199 Examples 7

Example 1

Project: pychess
Source File: model.py
View license
@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    # www.sqlite.org/pragma.html
    cursor.execute("PRAGMA page_size = 4096")
    cursor.execute("PRAGMA cache_size=10000")
    # cursor.execute("PRAGMA locking_mode=EXCLUSIVE")
    cursor.execute("PRAGMA synchronous=NORMAL")
    cursor.execute("PRAGMA journal_mode=WAL")
    # cursor.execute("PRAGMA foreign_keys=ON")
    cursor.close()

Example 2

Project: pygotham
Source File: models.py
View license
@event.listens_for(User, 'before_insert')
def user_create_send_password_reset(mapper, connection, target):
    """Send a password reset to users created without an email."""
    if not target.password:
        target.password = ''.join(
            random.choice(string.printable) for _ in range(20))
        recoverable.send_reset_password_instructions(target)

Example 3

Project: cleaver
Source File: session.py
View license
def session_for(dburi, **kwargs):
    engine = get_engine(dburi, **kwargs)
    if dburi not in _SESSIONS:
        _SESSIONS[dburi] = scoped_session(sessionmaker(bind=engine))
        ModelBase.query = _SESSIONS[dburi].query_property()

        # When a entity is instantiated, automatically add it to the Session
        @event.listens_for(mapper, 'init')
        def auto_add(target, args, kwargs):
            if isinstance(target, ModelBase):
                _SESSIONS[dburi].add(target)

    if not _SETUP['results']:
        ModelBase.metadata.create_all(engine)
        _SETUP['results'] = True

    return _SESSIONS[dburi]

Example 4

Project: pybossa
Source File: event_listeners.py
View license
@event.listens_for(Project, 'after_insert')
def add_project_event(mapper, conn, target):
    """Update PyBossa feed with new project."""
    obj = dict(id=target.id,
               name=target.name,
               short_name=target.short_name,
               action_updated='Project')
    update_feed(obj)

Example 5

Project: pybossa
Source File: event_listeners.py
View license
@event.listens_for(Task, 'after_insert')
def add_task_event(mapper, conn, target):
    """Update PyBossa feed with new task."""
    sql_query = ('select name, short_name, info from project \
                 where id=%s') % target.project_id
    results = conn.execute(sql_query)
    obj = dict(id=target.project_id,
               name=None,
               short_name=None,
               info=None,
               action_updated='Task')
    for r in results:
        obj['name'] = r.name
        obj['short_name'] = r.short_name
        obj['info'] = r.info
    update_feed(obj)

Example 6

Project: pybossa
Source File: event_listeners.py
View license
@event.listens_for(User, 'after_insert')
def add_user_event(mapper, conn, target):
    """Update PyBossa feed with new user."""
    obj = target.dictize()
    obj['action_updated']='User'
    update_feed(obj)

Example 7

Project: pybossa
Source File: event_listeners.py
View license
@event.listens_for(Blogpost, 'after_insert')
@event.listens_for(Blogpost, 'after_update')
@event.listens_for(Task, 'after_insert')
@event.listens_for(Task, 'after_update')
@event.listens_for(TaskRun, 'after_insert')
@event.listens_for(TaskRun, 'after_update')
def update_project(mapper, conn, target):
    """Update project updated timestamp."""
    update_project_timestamp(mapper, conn, target)

Example 8

Project: quicktill
Source File: td.py
View license
@event.listens_for(Pool, "checkout")
def ping_connection(dbapi_connection, connection_record, connection_proxy):
    cursor=dbapi_connection.cursor()
    try:
        cursor.execute("SELECT 1")
    except:
        raise exc.DisconnectionError()
    cursor.close()

Example 9

Project: piecash
Source File: kvp.py
View license
@event.listens_for(SlotFrame.slots, 'remove')
def remove_slot(target, value, initiator):
    s = object_session(value)
    if value in s.new:
        s.expunge(value)
    else:
        s.delete(value)

Example 10

Project: piecash
Source File: _declbase.py
View license
    @classmethod
    def __declare_last__(cls):
        # do not do it on the DeclarativeBaseGuid as it is an abstract class
        if cls == DeclarativeBaseGuid:
            return

        # assign id of slot when associating to object
        @event.listens_for(cls.slots, "remove")
        def my_append_listener_slots(target, value, initiator):
            s = object_session(value)
            if s:
                if value in s.new:
                    s.expunge(value)
                else:
                    s.delete(value)

Example 11

Project: king-phisher
Source File: manager.py
View license
@sqlalchemy.event.listens_for(Session, 'after_flush')
def on_session_after_flush(session, flush_context):
	for signal, session_attribute in _flush_signal_map:
		objs = collections.defaultdict(list)
		for obj in getattr(session, session_attribute):
			objs[obj.__tablename__].append(obj)
		for table, targets in objs.items():
			signals.safe_send(signal, logger, table, targets=tuple(targets), session=session)

Example 12

Project: king-phisher
Source File: manager.py
View license
@sqlalchemy.event.listens_for(Session, 'after_flush')
def on_session_after_flush(session, flush_context):
	for signal, session_attribute in _flush_signal_map:
		objs = collections.defaultdict(list)
		for obj in getattr(session, session_attribute):
			objs[obj.__tablename__].append(obj)
		for table, targets in objs.items():
			signals.safe_send(signal, logger, table, targets=tuple(targets), session=session)

Example 13

Project: beavy
Source File: models.py
View license
@event.listens_for(Like, 'after_insert')
def update_object_likes_count(mapper, connection, target):
    # unfortunately, we can't do an aggregate in update directly...
    likes_count = Like.query.filter(Like.object_id == target.object_id).count()
    Object.query.filter(Object.id == target.object_id
                        ).update({'likes_count': likes_count})

Example 14

Project: alembic
Source File: provision.py
View license
@_post_configure_engine.for_db("sqlite")
def _sqlite_post_configure_engine(url, engine, follower_ident):
    from sqlalchemy import event

    @event.listens_for(engine, "connect")
    def connect(dbapi_connection, connection_record):
        # use file DBs in all cases, memory acts kind of strangely
        # as an attached
        if not follower_ident:
            dbapi_connection.execute(
                'ATTACH DATABASE "test_schema.db" AS test_schema')
        else:
            dbapi_connection.execute(
                'ATTACH DATABASE "%s_test_schema.db" AS test_schema'
                % follower_ident)

Example 15

Project: sqlalchemy
Source File: generic_fk.py
View license
@event.listens_for(HasAddresses, "mapper_configured", propagate=True)
def setup_listener(mapper, class_):
    name = class_.__name__
    discriminator = name.lower()
    class_.addresses = relationship(Address,
                        primaryjoin=and_(
                                        class_.id == foreign(remote(Address.parent_id)),
                                        Address.discriminator == discriminator
                                    ),
                        backref=backref(
                                "parent_%s" % discriminator,
                                primaryjoin=remote(class_.id) == foreign(Address.parent_id)
                                )
                        )
    @event.listens_for(class_.addresses, "append")
    def append_address(target, value, initiator):
        value.discriminator = discriminator

Example 16

Project: sqlalchemy
Source File: history_meta.py
View license
def versioned_session(session):
    @event.listens_for(session, 'before_flush')
    def before_flush(session, flush_context, instances):
        for obj in versioned_objects(session.dirty):
            create_version(obj, session)
        for obj in versioned_objects(session.deleted):
            create_version(obj, session, deleted=True)

Example 17

Project: sqlalchemy
Source File: dictlike-polymorphic.py
View license
@event.listens_for(PolymorphicVerticalProperty, "mapper_configured", propagate=True)
def on_new_class(mapper, cls_):
    """Look for Column objects with type info in them, and work up
    a lookup table."""

    info_dict = {}
    info_dict[type(None)] = (None, 'none')
    info_dict['none'] = (None, 'none')

    for k in mapper.c.keys():
        col = mapper.c[k]
        if 'type' in col.info:
            python_type, discriminator = col.info['type']
            info_dict[python_type] = (k, discriminator)
            info_dict[discriminator] = (k, discriminator)
    cls_.type_map = info_dict

Example 18

Project: sqlalchemy
Source File: provision.py
View license
@_post_configure_engine.for_db("sqlite")
def _sqlite_post_configure_engine(url, engine, follower_ident):
    from sqlalchemy import event

    @event.listens_for(engine, "connect")
    def connect(dbapi_connection, connection_record):
        # use file DBs in all cases, memory acts kind of strangely
        # as an attached
        if not follower_ident:
            dbapi_connection.execute(
                'ATTACH DATABASE "test_schema.db" AS test_schema')
        else:
            dbapi_connection.execute(
                'ATTACH DATABASE "%s_test_schema.db" AS test_schema'
                % follower_ident)

Example 19

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

        canary = Mock()

        @event.listens_for(TargetOne, "event_one", named=True)
        def handler1(**kw):
            canary(kw)

        TargetOne().dispatch.event_one(4, 5)

        eq_(
            canary.mock_calls,
            [call({"x": 4, "y": 5})]
        )

Example 20

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

        canary = Mock()

        @event.listens_for(TargetOne, "event_one", named=True)
        def handler1(**kw):
            canary(kw)

        TargetOne().dispatch.event_one(4, 5)

        eq_(
            canary.mock_calls,
            [call({'y': 'adapted 5', 'x': 'adapted 4'})]
        )

Example 21

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

        canary = Mock()

        @event.listens_for(TargetOne, "event_five", named=True)
        def handler1(z, y, **kw):
            canary(z, y, kw)

        TargetOne().dispatch.event_five(4, 5, 6, 7)

        eq_(
            canary.mock_calls,
            [call(6, 5, {"x": 4, "q": 7})]
        )

Example 22

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

        canary = Mock()

        @event.listens_for(TargetOne, "event_five", named=True)
        def handler1(z, y, **kw):
            canary(z, y, kw)

        TargetOne().dispatch.event_five(4, 5, 6, 7)

        eq_(
            canary.mock_calls,
            [call('adapted 6', 'adapted 5',
             {'q': 'adapted 7', 'x': 'adapted 4'})]
        )

Example 23

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

        @event.listens_for(TargetOne, "event_two", named=True)
        def handler1(**kw):
            canary(kw)

        TargetOne().dispatch.event_two(4, 5, z=8, q=5)

        eq_(
            canary.mock_calls,
            [call({"x": 4, "y": 5, "z": 8, "q": 5})]
        )

Example 24

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

        @event.listens_for(self.TargetOne, "event_three")
        def handler1(x, y):
            canary(x, y)

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

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

Example 25

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

        @event.listens_for(self.TargetOne, "event_four")
        def handler1(x, y, **kw):
            canary(x, y, kw)
        self._test_legacy_accept_kw(self.TargetOne(), canary)

Example 26

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

        inst = self.TargetOne()

        @event.listens_for(inst, "event_four")
        def handler1(x, y, **kw):
            canary(x, y, kw)
        self._test_legacy_accept_kw(inst, canary)

Example 27

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

        @event.listens_for(self.TargetOne, "event_six")
        def handler1(x, y, z, q):
            canary(x, y, z, q)

        self.TargetOne().dispatch.event_six(4, 5)
        eq_(
            canary.mock_calls,
            [call(4, 5, 9, 20)]
        )

Example 28

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

        @event.listens_for(self.TargetOne, "event_three", named=True)
        def handler1(**kw):
            canary(kw)

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

        eq_(
            canary.mock_calls,
            [call({"x": 4, "y": 5, "z": 6, "q": 7})]
        )

Example 29

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

        @event.listens_for(self.TargetOne, "event_four", named=True)
        def handler1(**kw):
            canary(kw)

        self.TargetOne().dispatch.event_four(4, 5, 6, 7, foo="bar")

        eq_(
            canary.mock_calls,
            [call({"x": 4, "y": 5, "z": 6, "q": 7, "foo": "bar"})]
        )

Example 30

Project: sqlalchemy
Source File: test_events.py
View license
    def test_lis_subcalss_lis(self):
        @event.listens_for(self.TargetOne, "event_one")
        def handler1(x, y):
            pass

        class SubTarget(self.TargetOne):
            pass

        @event.listens_for(self.TargetOne, "event_one")
        def handler2(x, y):
            pass

        eq_(
            len(SubTarget().dispatch.event_one),
            2
        )

Example 31

Project: sqlalchemy
Source File: test_query.py
View license
    @testing.provide_metadata
    def test_insertid_schema(self):
        meta = self.metadata
        eng = engines.testing_engine(
            options=dict(legacy_schema_aliasing=False))
        meta.bind = eng
        con = eng.connect()
        con.execute('create schema paj')

        @event.listens_for(meta, "after_drop")
        def cleanup(target, connection, **kw):
            connection.execute('drop schema paj')

        tbl = Table('test', meta,
                    Column('id', Integer, primary_key=True), schema='paj')
        tbl.create()
        tbl.insert().execute({'id': 1})
        eq_(tbl.select().scalar(), 1)

Example 32

Project: sqlalchemy
Source File: test_query.py
View license
    @testing.provide_metadata
    def test_insertid_schema_legacy(self):
        meta = self.metadata
        eng = engines.testing_engine(
            options=dict(legacy_schema_aliasing=True))
        meta.bind = eng
        con = eng.connect()
        con.execute('create schema paj')

        @event.listens_for(meta, "after_drop")
        def cleanup(target, connection, **kw):
            connection.execute('drop schema paj')

        tbl = Table('test', meta,
                    Column('id', Integer, primary_key=True), schema='paj')
        tbl.create()
        tbl.insert().execute({'id': 1})
        eq_(tbl.select().scalar(), 1)

Example 33

Project: sqlalchemy
Source File: test_query.py
View license
    @classmethod
    def setup_bind(cls):
        from sqlalchemy import event
        eng = engines.testing_engine()

        @event.listens_for(eng, "connect")
        def connect(dbapi_conn, rec):
            cursor = dbapi_conn.cursor()
            cursor.execute("SET SESSION TIME ZONE 0")
            cursor.close()

        return eng

Example 34

Project: sqlalchemy
Source File: test_horizontal_shard.py
View license
    def _init_dbs(self):
        db1 = testing_engine('sqlite://', options={"execution_options":
                                            {"shard_id": "shard1"}})
        db2 = db1.execution_options(shard_id="shard2")
        db3 = db1.execution_options(shard_id="shard3")
        db4 = db1.execution_options(shard_id="shard4")

        import re
        @event.listens_for(db1, "before_cursor_execute", retval=True)
        def _switch_shard(conn, cursor, stmt, params, context, executemany):
            shard_id = conn._execution_options['shard_id']
            # because SQLite can't just give us a "use" statement, we have
            # to use the schema hack to locate table names
            if shard_id:
                stmt = re.sub(r"\"?changeme\"?\.", shard_id + "_", stmt)

            return stmt, params

        return db1, db2, db3, db4

Example 35

Project: sqlalchemy
Source File: test_transaction.py
View license
    def test_continue_flushing_guard(self):
        users, User = self.tables.users, self.classes.User

        mapper(User, users)
        sess = Session()

        @event.listens_for(sess, "after_flush_postexec")
        def add_another_user(session, ctx):
            session.add(User(name='x'))
        sess.add(User(name='x'))
        assert_raises_message(
            orm_exc.FlushError,
            "Over 100 subsequent flushes have occurred",
            sess.commit
        )

Example 36

Project: sqlalchemy
Source File: test_transaction.py
View license
    def test_no_sql_during_commit(self):
        sess = create_session(bind=testing.db, autocommit=False)

        @event.listens_for(sess, "after_commit")
        def go(session):
            session.execute("select 1")
        assert_raises_message(
            sa_exc.InvalidRequestError,
            "This session is in 'committed' state; no further "
            "SQL can be emitted within this transaction.",
            sess.commit)

Example 37

Project: faf
Source File: events.py
View license
@event.listens_for(ReportBtFrame, "init")
def init_btframe(target, args, kwargs):
    """
    Set reliable to True so it has default set correctly
    before it's stored in the database
    """
    target.reliable = True

Example 38

Project: faf
Source File: events.py
View license
@event.listens_for(Session, "before_flush")
def update_backtrace_quality(session, flush_context, instances):
    """
    Compute and store backtrace quality information
    """

    objects = session.new.union(session.dirty)
    for obj in [c for c in objects if isinstance(c, ReportBacktrace)]:
        if isinstance(obj, ReportBacktrace):
            obj.quality = obj.compute_quality()

Example 39

Project: faf
Source File: events.py
View license
@event.listens_for(mapper, 'before_delete')
def before_delete(mapper, connection, target):
    """
    Remove lobs associated with target to be deleted.
    """

    for lobname in target.__lobs__:
        if target.has_lob(lobname):
            target.del_lob(lobname)

Example 40

Project: faf
Source File: events.py
View license
@event.listens_for(Build.version, "set")
def store_semantic_version_for_build(target, value, oldvalue, initiator):
    """
    Store semnatic version (Build.semver) converted from text version
    (Build.version)
    """

    target.semver = value

Example 41

Project: faf
Source File: events.py
View license
@event.listens_for(Build.release, "set")
def store_semantic_release_for_build(target, value, oldvalue, initiator):
    """
    Store semnatic release (Build.semrel) converted from text release
    (Build.release)
    """

    target.semrel = value

Example 42

Project: bigmetadata
Source File: meta.py
View license
def get_engine():

    @event.listens_for(_engine, "connect")
    def connect(dbapi_connection, connection_record):
        connection_record.info['pid'] = os.getpid()

    @event.listens_for(_engine, "checkout")
    def checkout(dbapi_connection, connection_record, connection_proxy):
        pid = os.getpid()
        if connection_record.info['pid'] != pid:
            connection_record.connection = connection_proxy.connection = None
            raise exc.DisconnectionError(
                "Connection record belongs to pid %s, "
                "attempting to check out in pid %s" %
                (connection_record.info['pid'], pid)
            )
    return _engine

Example 43

Project: crate-python
Source File: compiler.py
View license
@sa.event.listens_for(sa.engine.Engine, "before_execute", retval=True)
def crate_before_execute(conn, clauseelement, multiparams, params):
    is_crate = type(conn.dialect).__name__ == 'CrateDialect'
    if is_crate and isinstance(clauseelement, sa.sql.expression.Update):
        return rewrite_update(clauseelement, multiparams, params)
    return clauseelement, multiparams, params

Example 44

Project: caravel
Source File: utils.py
View license
def pessimistic_connection_handling(target):
    @event.listens_for(target, "checkout")
    def ping_connection(dbapi_connection, connection_record, connection_proxy):
        """
        Disconnect Handling - Pessimistic, taken from:
        http://docs.sqlalchemy.org/en/rel_0_9/core/pooling.html
        """
        cursor = dbapi_connection.cursor()
        try:
            cursor.execute("SELECT 1")
        except:
            raise exc.DisconnectionError()
        cursor.close()

Example 45

Project: superset
Source File: utils.py
View license
def pessimistic_connection_handling(target):
    @event.listens_for(target, "checkout")
    def ping_connection(dbapi_connection, connection_record, connection_proxy):
        """
        Disconnect Handling - Pessimistic, taken from:
        http://docs.sqlalchemy.org/en/rel_0_9/core/pooling.html
        """
        cursor = dbapi_connection.cursor()
        try:
            cursor.execute("SELECT 1")
        except:
            raise exc.DisconnectionError()
        cursor.close()

Example 46

Project: djorm-ext-pool
Source File: __init__.py
View license
@event.listens_for(Pool, "checkout")
def _on_checkout(dbapi_connection, connection_record, connection_proxy):
    logger.debug("connection retrieved from pool")

    if POOL_PESSIMISTIC_MODE:
        cursor = dbapi_connection.cursor()
        try:
            cursor.execute("SELECT 1")
        except:
            # raise DisconnectionError - pool will try
            # connecting again up to three times before raising.
            raise exc.DisconnectionError()
        finally:
            cursor.close()

Example 47

Project: changes
Source File: conftest.py
View license
@pytest.fixture(scope='session', autouse=True)
def setup_db(request, app, session_config):
    db_name = session_config['db_name']
    # 9.1 does not support --if-exists
    if os.system("psql -l | grep '%s'" % db_name) == 0:
        assert not os.system('dropdb %s' % db_name)
    assert not os.system('createdb -E utf-8 %s' % db_name)

    command.upgrade(alembic_cfg, 'head')

    @event.listens_for(Session, "after_transaction_end")
    def restart_savepoint(session, transaction):
        if transaction.nested and not transaction._parent.nested:
            session.begin_nested()

Example 48

Project: stalker
Source File: repository.py
View license
@event.listens_for(Repository, 'after_insert')
def receive_after_insert(mapper, connection, repo):
    """listen for the 'after_insert' event
    """
    logger.debug('auto creating env var for Repository with id: %s' % repo.id)
    os.environ[defaults.repo_env_var_template % {'id': repo.id}] = repo.path

Example 49

Project: flask-admin
Source File: app.py
View license
@event.listens_for(LocationImage, 'after_delete')
def _handle_image_delete(mapper, conn, target):
    try:
        if target.path:
            os.remove(op.join(base_path, target.path))
    except:
        pass

Example 50

Project: open-event-orga-server
Source File: event.py
View license
@event.listens_for(Event, 'after_insert')
def receive_init(mapper, conn, target):
    custom_form = CustomForms(
        event_id=target.id,
        session_form=session_form_str,
        speaker_form=speaker_form_str
    )
    target.custom_forms.append(custom_form)