当前位置: 首页>>代码示例>>Python>>正文


Python event.listens_for方法代码示例

本文整理汇总了Python中sqlalchemy.event.listens_for方法的典型用法代码示例。如果您正苦于以下问题:Python event.listens_for方法的具体用法?Python event.listens_for怎么用?Python event.listens_for使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sqlalchemy.event的用法示例。


在下文中一共展示了event.listens_for方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: instrument_class

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def instrument_class(self, mapper, class_):
        """Receive a class when the mapper is first constructed,
        before instrumentation is applied to the mapped class.

        This event is the earliest phase of mapper construction.
        Most attributes of the mapper are not yet initialized.

        This listener can either be applied to the :class:`.Mapper`
        class overall, or to any un-mapped class which serves as a base
        for classes that will be mapped (using the ``propagate=True`` flag)::

            Base = declarative_base()

            @event.listens_for(Base, "instrument_class", propagate=True)
            def on_new_class(mapper, cls_):
                " ... "

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param class\_: the mapped class.

        """ 
开发者ID:jpush,项目名称:jbox,代码行数:24,代码来源:events.py

示例2: before_compile

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def before_compile(self, query):
        """Receive the :class:`.Query` object before it is composed into a
        core :class:`.Select` object.

        This event is intended to allow changes to the query given::

            @event.listens_for(Query, "before_compile", retval=True)
            def no_deleted(query):
                for desc in query.column_descriptions:
                    if desc['type'] is User:
                        entity = desc['entity']
                        query = query.filter(entity.deleted == False)
                return query

        The event should normally be listened with the ``retval=True``
        parameter set, so that the modified query may be returned.


        """ 
开发者ID:jpush,项目名称:jbox,代码行数:21,代码来源:events.py

示例3: init_session

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def init_session(request, configuration_loaded):
    # Init registry
    additional_setting = {'unittest': True}

    if len(BlokManager.list()) == 0:
        BlokManager.load()
    registry = RegistryManager.get(Configuration.get('db_name'),
                                   **additional_setting)
    registry.commit()
    # Add savepoint
    registry.begin_nested()

    @event.listens_for(registry.session, 'after_transaction_end')
    def restart_savepoint(session, transaction):
        if transaction.nested and not transaction._parent.nested:
            session.expire_all()
            session.begin_nested()

    logger.info('Creating registry')
    yield registry

    request.addfinalizer(registry.session.close) 
开发者ID:AnyBlok,项目名称:AnyBlok,代码行数:24,代码来源:conftest.py

示例4: capture_engine_context_buffer

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def capture_engine_context_buffer(**kw):
    from .env import _sqlite_file_db
    from sqlalchemy import event

    buf = compat.StringIO()

    eng = _sqlite_file_db()

    conn = eng.connect()

    @event.listens_for(conn, "before_cursor_execute")
    def bce(conn, cursor, statement, parameters, context, executemany):
        buf.write(statement + "\n")

    kw.update({"connection": conn})
    conf = EnvironmentContext.configure

    def configure(*arg, **opt):
        opt.update(**kw)
        return conf(*arg, **opt)

    with mock.patch.object(EnvironmentContext, "configure", configure):
        yield buf 
开发者ID:sqlalchemy,项目名称:alembic,代码行数:25,代码来源:fixtures.py

示例5: _make_engine_thread_safe

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def _make_engine_thread_safe(engine):
    """Make the engine even more thread safe than by default.

    The code is taken from the documentation: https://tinyurl.com/u9xea5z

    The main purpose is to emit the begin statement of any connection
    as late as possible in order to keep the time in which the database
    is locked as short as possible.

    """

    @event.listens_for(engine, "connect")
    def do_connect(dbapi_connection, connection_record):
        # disable pysqlite's emitting of the BEGIN statement entirely.
        # also stops it from emitting COMMIT before absolutely necessary.
        dbapi_connection.isolation_level = None

    @event.listens_for(engine, "begin")
    def do_begin(conn):
        # emit our own BEGIN
        conn.execute("BEGIN DEFERRED") 
开发者ID:OpenSourceEconomics,项目名称:estimagic,代码行数:23,代码来源:create_database.py

示例6: instrument_class

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def instrument_class(self, mapper, class_):
        r"""Receive a class when the mapper is first constructed,
        before instrumentation is applied to the mapped class.

        This event is the earliest phase of mapper construction.
        Most attributes of the mapper are not yet initialized.

        This listener can either be applied to the :class:`.Mapper`
        class overall, or to any un-mapped class which serves as a base
        for classes that will be mapped (using the ``propagate=True`` flag)::

            Base = declarative_base()

            @event.listens_for(Base, "instrument_class", propagate=True)
            def on_new_class(mapper, cls_):
                " ... "

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param class\_: the mapped class.

        """ 
开发者ID:yfauser,项目名称:planespotter,代码行数:24,代码来源:events.py

示例7: listens_for

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def listens_for(target, identifier, *args, **kw):
    """Decorate a function as a listener for the given target + identifier.

    e.g.::

        from sqlalchemy import event
        from sqlalchemy.schema import UniqueConstraint

        @event.listens_for(UniqueConstraint, "after_parent_attach")
        def unique_constraint_name(const, table):
            const.name = "uq_%s_%s" % (
                table.name,
                list(const.columns)[0].name
            )

    A given function can also be invoked for only the first invocation
    of the event using the ``once`` argument::

        @event.listens_for(Mapper, "before_configure", once=True)
        def on_config():
            do_config()


    .. versionadded:: 0.9.4 Added ``once=True`` to :func:`.event.listen`
       and :func:`.event.listens_for`.

    .. seealso::

        :func:`.listen` - general description of event listening

    """
    def decorate(fn):
        listen(target, identifier, fn, *args, **kw)
        return fn
    return decorate 
开发者ID:jpush,项目名称:jbox,代码行数:37,代码来源:api.py

示例8: _sqlite_post_configure_engine

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
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) 
开发者ID:jpush,项目名称:jbox,代码行数:16,代码来源:provision.py

示例9: after_soft_rollback

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def after_soft_rollback(self, session, previous_transaction):
        """Execute after any rollback has occurred, including "soft"
        rollbacks that don't actually emit at the DBAPI level.

        This corresponds to both nested and outer rollbacks, i.e.
        the innermost rollback that calls the DBAPI's
        rollback() method, as well as the enclosing rollback
        calls that only pop themselves from the transaction stack.

        The given :class:`.Session` can be used to invoke SQL and
        :meth:`.Session.query` operations after an outermost rollback
        by first checking the :attr:`.Session.is_active` flag::

            @event.listens_for(Session, "after_soft_rollback")
            def do_something(session, previous_transaction):
                if session.is_active:
                    session.execute("select * from some_table")

        :param session: The target :class:`.Session`.
        :param previous_transaction: The :class:`.SessionTransaction`
         transactional marker object which was just closed.   The current
         :class:`.SessionTransaction` for the given :class:`.Session` is
         available via the :attr:`.Session.transaction` attribute.

        .. versionadded:: 0.7.3

        """ 
开发者ID:jpush,项目名称:jbox,代码行数:29,代码来源:events.py

示例10: before_execute

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def before_execute(self, conn, clauseelement, multiparams, params):
        """Intercept high level execute() events, receiving uncompiled
        SQL constructs and other objects prior to rendering into SQL.

        This event is good for debugging SQL compilation issues as well
        as early manipulation of the parameters being sent to the database,
        as the parameter lists will be in a consistent format here.

        This event can be optionally established with the ``retval=True``
        flag.  The ``clauseelement``, ``multiparams``, and ``params``
        arguments should be returned as a three-tuple in this case::

            @event.listens_for(Engine, "before_execute", retval=True)
            def before_execute(conn, conn, clauseelement, multiparams, params):
                # do something with clauseelement, multiparams, params
                return clauseelement, multiparams, params

        :param conn: :class:`.Connection` object
        :param clauseelement: SQL expression construct, :class:`.Compiled`
         instance, or string statement passed to :meth:`.Connection.execute`.
        :param multiparams: Multiple parameter sets, a list of dictionaries.
        :param params: Single parameter set, a single dictionary.

        See also:

        :meth:`.before_cursor_execute`

        """ 
开发者ID:jpush,项目名称:jbox,代码行数:30,代码来源:events.py

示例11: before_cursor_execute

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def before_cursor_execute(self, conn, cursor, statement,
                              parameters, context, executemany):
        """Intercept low-level cursor execute() events before execution,
        receiving the string SQL statement and DBAPI-specific parameter list to
        be invoked against a cursor.

        This event is a good choice for logging as well as late modifications
        to the SQL string.  It's less ideal for parameter modifications except
        for those which are specific to a target backend.

        This event can be optionally established with the ``retval=True``
        flag.  The ``statement`` and ``parameters`` arguments should be
        returned as a two-tuple in this case::

            @event.listens_for(Engine, "before_cursor_execute", retval=True)
            def before_cursor_execute(conn, cursor, statement,
                            parameters, context, executemany):
                # do something with statement, parameters
                return statement, parameters

        See the example at :class:`.ConnectionEvents`.

        :param conn: :class:`.Connection` object
        :param cursor: DBAPI cursor object
        :param statement: string SQL statement, as to be passed to the DBAPI
        :param parameters: Dictionary, tuple, or list of parameters being
         passed to the ``execute()`` or ``executemany()`` method of the
         DBAPI ``cursor``.  In some cases may be ``None``.
        :param context: :class:`.ExecutionContext` object in use.  May
         be ``None``.
        :param executemany: boolean, if ``True``, this is an ``executemany()``
         call, if ``False``, this is an ``execute()`` call.

        See also:

        :meth:`.before_execute`

        :meth:`.after_cursor_execute`

        """ 
开发者ID:jpush,项目名称:jbox,代码行数:42,代码来源:events.py

示例12: versioned_session

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
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) 
开发者ID:rucio,项目名称:rucio,代码行数:9,代码来源:history.py

示例13: connection_event

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def connection_event():
    @event.listens_for(Pool, "checkout")
    def ping_connection(dbapi_connection, connection_record, connection_proxy):
        # 在每次从连接池获取一个连接时,首先测试连接池是否畅通
        # 如果不畅通,则断开重新建立连接,及时防丢
        cursor = dbapi_connection.cursor()
        try:
            cursor.execute("SELECT 1")
        except:
            SysLogger.error('database pool has gone away')
            connection_proxy._pool.dispose()
        cursor.close() 
开发者ID:mqingyn,项目名称:torngas,代码行数:14,代码来源:dbalchemy.py

示例14: init

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def init(url):
        DBManager.engine = create_engine(url, pool_pre_ping=True, pool_size=10, max_overflow=20)

        # https://docs.sqlalchemy.org/en/13/core/events.html#sqlalchemy.events.PoolEvents.connect
        @event.listens_for(DBManager.engine, "connect")
        def on_connect(dbapi_connection, connection_record):
            # http://initd.org/psycopg/docs/connection.html#connection.notices
            # > The notices attribute is writable: the user may replace it with any Python object
            # > exposing an append() method. If appending raises an exception the notice is silently dropped.
            # This replaces the list object with a logger that logs the incoming notices
            dbapi_connection.notices = ServerNoticeLogger()

        DBManager.Session = sessionmaker(bind=DBManager.engine, autoflush=False)
        DBManager.ScopedSession = scoped_session(sessionmaker(bind=DBManager.engine)) 
开发者ID:pajbot,项目名称:pajbot,代码行数:16,代码来源:db.py

示例15: _seed

# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listens_for [as 别名]
def _seed(self):
        result = BaseTest._seed(self)

        self.query_count = 0

        @event.listens_for(sess.connection(), 'before_cursor_execute')
        def before_cursor_execute(conn, cursor, statement, parameters,
                                  context, executemany):
            self.query_count += 1

        return result 
开发者ID:absent1706,项目名称:sqlalchemy-mixins,代码行数:13,代码来源:test_smartquery.py


注:本文中的sqlalchemy.event.listens_for方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。