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


Python exc.DisconnectionError方法代码示例

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


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

示例1: mysql_ping_listener

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DisconnectionError [as 别名]
def mysql_ping_listener(dbapi_conn, connection_rec, connection_proxy):
    """
    Ensures that MySQL connections checked out of the
    pool are alive.

    Borrowed from:
    http://groups.google.com/group/sqlalchemy/msg/a4ce563d802c929f

    :param dbapi_conn: DBAPI connection
    :param connection_rec: connection record
    :param connection_proxy: connection proxy
    """

    try:
        dbapi_conn.cursor().execute('select 1')
    except dbapi_conn.OperationalError as ex:
        if ex.args[0] in (2006, 2013, 2014, 2045, 2055):
            msg = 'Got mysql server has gone away: %s' % ex
            raise DisconnectionError(msg)
        else:
            raise 
开发者ID:rucio,项目名称:rucio,代码行数:23,代码来源:session.py

示例2: _ping_listener

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DisconnectionError [as 别名]
def _ping_listener(dbapi_conn, connection_rec, connection_proxy):
    """Ensures that MySQL connections checked out of the pool are alive.

    Modified + borrowed from: http://bit.ly/14BYaW6.
    """
    try:
        dbapi_conn.cursor().execute('select 1')
    except dbapi_conn.OperationalError as ex:
        if _in_any(six.text_type(ex.args[0]), MY_SQL_GONE_WAY_AWAY_ERRORS):
            LOG.warning('Got mysql server has gone away', exc_info=True)
            raise sa_exc.DisconnectionError("Database server went away")
        elif _in_any(six.text_type(ex.args[0]), POSTGRES_GONE_WAY_AWAY_ERRORS):
            LOG.warning('Got postgres server has gone away', exc_info=True)
            raise sa_exc.DisconnectionError("Database server went away")
        else:
            raise 
开发者ID:openstack,项目名称:taskflow,代码行数:18,代码来源:impl_sqlalchemy.py

示例3: checkout

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DisconnectionError [as 别名]
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)
        ) 
开发者ID:softwarefactory-project,项目名称:DLRN,代码行数:11,代码来源:db.py

示例4: ping_connection

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DisconnectionError [as 别名]
def ping_connection(dbapi_connection, connection_record, connection_proxy):
    cursor = dbapi_connection.cursor()
    try:
        cursor.execute("SELECT 1")
    except:
        # optional - dispose the whole pool
        # instead of invalidating one at a time
        # connection_proxy._pool.dispose()

        # raise DisconnectionError - pool will try
        # connecting again up to three times before raising.
        raise exc.DisconnectionError()
    cursor.close() 
开发者ID:ourresearch,项目名称:depsy,代码行数:15,代码来源:app.py

示例5: validate

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DisconnectionError [as 别名]
def validate(self, max_retries=0):
        """Performs basic **connection** validation of a sqlalchemy engine."""

        def _retry_on_exception(exc):
            LOG.warning("Engine connection (validate) failed due to '%s'", exc)
            if isinstance(exc, sa_exc.OperationalError) and \
               _is_db_connection_error(six.text_type(exc.args[0])):
                # We may be able to fix this by retrying...
                return True
            if isinstance(exc, (sa_exc.TimeoutError,
                                sa_exc.ResourceClosedError,
                                sa_exc.DisconnectionError)):
                # We may be able to fix this by retrying...
                return True
            # Other failures we likely can't fix by retrying...
            return False

        @tenacity.retry(
            stop=tenacity.stop_after_attempt(max(0, int(max_retries))),
            wait=tenacity.wait_exponential(),
            reraise=True,
            retry=tenacity.retry_if_exception(_retry_on_exception)
        )
        def _try_connect(engine):
            # See if we can make a connection happen.
            #
            # NOTE(harlowja): note that even though we are connecting
            # once it does not mean that we will be able to connect in
            # the future, so this is more of a sanity test and is not
            # complete connection insurance.
            with contextlib.closing(engine.connect()):
                pass

        _try_connect(self._engine) 
开发者ID:openstack,项目名称:taskflow,代码行数:36,代码来源:impl_sqlalchemy.py

示例6: _add_process_guards

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DisconnectionError [as 别名]
def _add_process_guards(engine):
    """Add multiprocessing guards.

    Forces a connection to be reconnected if it is detected
    as having been shared to a sub-process.

    """

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

    @sqlalchemy.event.listens_for(engine, "checkout")
    def checkout(dbapi_connection, connection_record, connection_proxy):
        pid = os.getpid()
        if connection_record.info['pid'] != pid:
            LOG.debug(
                "Parent process %(orig)s forked (%(newproc)s) with an open "
                "database connection, "
                "which is being discarded and recreated.",
                {"newproc": pid, "orig": connection_record.info['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)
            ) 
开发者ID:openstack,项目名称:oslo.db,代码行数:29,代码来源:engines.py

示例7: ping_connection

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DisconnectionError [as 别名]
def ping_connection(dbapi_connection, connection_record, connection_proxy): # pylint: disable=unused-argument
    cursor = dbapi_connection.cursor()
    try:
        cursor.execute("SELECT 1")
        cursor.close()
    except:
        logging.info('fail to ping database server, disposing all cached connections')
        connection_proxy._pool.dispose() # pylint: disable=protected-access

        # Raise DisconnectionError so the pool would create a new connection
        raise DisconnectionError() 
开发者ID:haiwen,项目名称:seafobj,代码行数:13,代码来源:db.py

示例8: ping_connection

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DisconnectionError [as 别名]
def ping_connection(dbapi_connection, connection_record, connection_proxy):
    cursor = dbapi_connection.cursor()
    try:
        cursor.execute("SELECT 1")
    except Exception:  # pragma: no cover
        # optional - dispose the whole pool
        # instead of invalidating one at a time
        connection_proxy._pool.dispose()

        # raise DisconnectionError - pool will try
        # connecting again up to three times before raising.
        raise exc.DisconnectionError()
    cursor.close() 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:15,代码来源:db.py

示例9: checkout

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

示例10: setup_event_handlers

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import DisconnectionError [as 别名]
def setup_event_handlers(engine):
    """
    Setups event handlers.
    """
    # pylint: disable=unused-argument, unused-variable
    @event.listens_for(engine, "connect")
    def connect(dbapi_connection, connection_record):
        connection_record.info['pid'] = os.getpid()

    if engine.dialect.name == "sqlite":
        @event.listens_for(engine, "connect")
        def set_sqlite_pragma(dbapi_connection, connection_record):
            cursor = dbapi_connection.cursor()
            cursor.execute("PRAGMA foreign_keys=ON")
            cursor.close()

    # this ensures sanity in mysql when storing datetimes (not required for postgres)
    if engine.dialect.name == "mysql":
        @event.listens_for(engine, "connect")
        def set_mysql_timezone(dbapi_connection, connection_record):
            cursor = dbapi_connection.cursor()
            cursor.execute("SET time_zone = '+00:00'")
            cursor.close()

    @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 {}, "
                "attempting to check out in pid {}".format(connection_record.info['pid'], pid)
            )
    if conf.getboolean('debug', 'sqlalchemy_stats', fallback=False):
        @event.listens_for(engine, "before_cursor_execute")
        def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
            conn.info.setdefault('query_start_time', []).append(time.time())

        @event.listens_for(engine, "after_cursor_execute")
        def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
            total = time.time() - conn.info['query_start_time'].pop()
            file_name = [
                f"'{f.name}':{f.filename}:{f.lineno}" for f
                in traceback.extract_stack() if 'sqlalchemy' not in f.filename][-1]
            stack = [f for f in traceback.extract_stack() if 'sqlalchemy' not in f.filename]
            stack_info = ">".join([f"{f.filename.rpartition('/')[-1]}:{f.name}" for f in stack][-3:])
            conn.info.setdefault('query_start_time', []).append(time.monotonic())
            log.info("@SQLALCHEMY %s |$ %s |$ %s |$  %s ",
                     total, file_name, stack_info, statement.replace("\n", " ")
                     )
    # pylint: enable=unused-argument, unused-variable 
开发者ID:apache,项目名称:airflow,代码行数:53,代码来源:orm_event_handlers.py


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