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


Python exc.ResourceClosedError方法代码示例

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


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

示例1: test_used_with_begin_nested

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def test_used_with_begin_nested(self, session, assert_session):
        @transaction(session)
        def create_user(commit_inner):
            with session.begin_nested():
                user = User(username='test1', email='1@b.com', password='1')
                session.add(user)

            with session.begin_nested():
                user = User(username='test2', email='2@b.com', password='1')
                session.add(user)
            if commit_inner:
                session.commit()

        create_user(commit_inner=False)
        assert len(assert_session.query(User).all()) == 2

        self.clear_user()
        msg = 'This transaction is closed'
        with pytest.raises(ResourceClosedError, match=msg):
            create_user(commit_inner=True)
        assert len(assert_session.query(User).all()) == 0 
开发者ID:TTWShell,项目名称:hobbit-core,代码行数:23,代码来源:test_db.py

示例2: test_nested_self_raise

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def test_nested_self_raise(self, session, assert_session):
        @transaction(session)
        def create_user():
            user = User(username='test1', email='1@b.com', password='1')
            db.session.add(user)

        @transaction(session)
        def view_func():
            user = User(username='test2', email='2@b.com', password='1')
            db.session.add(user)
            create_user()

        if session.autocommit is False:
            msg = 'This transaction is closed'
            with pytest.raises(ResourceClosedError, match=msg):
                view_func()
        else:
            msg = r'A transaction is already begun.*'
            with pytest.raises(InvalidRequestError, match=msg):
                view_func()
        assert len(assert_session.query(User).all()) == 0 
开发者ID:TTWShell,项目名称:hobbit-core,代码行数:23,代码来源:test_db.py

示例3: test_connectionless_autoclose_no_metadata

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def test_connectionless_autoclose_no_metadata(self):
        # TODO: deprecate for 2.0
        result = testing.db.execute(text("update users set user_id=5"))
        connection = result.connection
        assert connection.closed

        assert_raises_message(
            exc.ResourceClosedError,
            "This result object does not return rows.",
            result.fetchone,
        )
        assert_raises_message(
            exc.ResourceClosedError,
            "This result object does not return rows.",
            result.keys,
        ) 
开发者ID:sqlalchemy,项目名称:sqlalchemy,代码行数:18,代码来源:test_resultset.py

示例4: update_repo_directory

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def update_repo_directory(ctx, repo_directory):
    """
    Update Facade worker repo cloning directory
    """
    app = ctx.obj

    db = get_db_connection(app)

    updateRepoDirectorySQL = s.sql.text("""
        UPDATE augur_data.settings SET VALUE = :repo_directory WHERE setting='repo_directory';
    """)

    try:
        pd.read_sql(updateRepoDirectorySQL, db, params={'repo_directory': repo_directory})
    except exc.ResourceClosedError as error:
        print(f"Successfully updated the Facade worker repo directory.")
        # pd.read_sql() will throw an AttributeError when it can't sucessfully "fetch" any rows from the result.
        # Since there's no rows to fetch after a successful insert, this is how we know it worked.
        # I know it's weird, sue me (jk please don't)

# get_db_version is a helper function to print_db_version and upgrade_db_version 
开发者ID:chaoss,项目名称:augur,代码行数:23,代码来源:db.py

示例5: test_used_with_commit_raised

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def test_used_with_commit_raised(self, session, assert_session):
        @transaction(session)
        def create_user():
            user = User(username='test1', email='1@b.com', password='1')
            session.add(user)
            session.commit()

        msg = 'This transaction is closed'
        with pytest.raises(ResourceClosedError, match=msg):
            create_user()
        assert assert_session.query(User).all() == [] 
开发者ID:TTWShell,项目名称:hobbit-core,代码行数:13,代码来源:test_db.py

示例6: test_nested_self_with_nested_arg_is_true_commit_raise

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def test_nested_self_with_nested_arg_is_true_commit_raise(
            self, session, assert_session):
        @transaction(session, nested=True)
        def create_user():
            user = User(username='test1', email='1@b.com', password='1')
            session.add(user)
            session.commit()

        @transaction(session)
        def view_func():
            create_user()

        msg = r'This transaction is closed'
        with pytest.raises(ResourceClosedError, match=msg):
            view_func() 
开发者ID:TTWShell,项目名称:hobbit-core,代码行数:17,代码来源:test_db.py

示例7: test_notautocommit_use_nested_alone_commit_raise

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def test_notautocommit_use_nested_alone_commit_raise(self, db_session):
        @transaction(db_session, nested=True)
        def create_user():
            user = User(username='test1', email='1@b.com', password='1')
            db_session.add(user)
            db_session.commit()

        msg = 'This transaction is closed'
        with pytest.raises(ResourceClosedError, match=msg):
            create_user() 
开发者ID:TTWShell,项目名称:hobbit-core,代码行数:12,代码来源:test_db.py

示例8: get_version

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def get_version(sql):
    table_info = "PRAGMA table_info('migrations')"
    from sqlalchemy.exc import ResourceClosedError
    try:
        if not sql.execute(table_info).fetchall():
            return 0
    except ResourceClosedError as e:
        if 'does not return rows' in str(e):
            return 0
    version_query = "SELECT version from migrations"
    version = sql.execute(version_query).fetchone()
    return version and version[0] or 0 
开发者ID:gdassori,项目名称:spruned,代码行数:14,代码来源:__init__.py

示例9: get_connection

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def get_connection(self):
        """Get a connection to this Database. Connections are retrieved from a
        pool.
        """
        if not self.open:
            raise exc.ResourceClosedError('Database closed.')

        return Connection(self._engine.connect()) 
开发者ID:kennethreitz-archive,项目名称:records,代码行数:10,代码来源:records.py

示例10: do_exec

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def do_exec(args):
            msg, sql = args
            with log_duration(msg):
                with engine.begin() as trans:
                    res = trans.execute(sql)
                    try:
                        logger.info(f"SQL result", job=msg, result=res.fetchall())
                    except ResourceClosedError:
                        pass  # Nothing to do here
                    except Exception as exc:
                        logger.error("Hit an issue.", exc=exc)
                        raise exc 
开发者ID:Flowminder,项目名称:FlowKit,代码行数:14,代码来源:generate_synthetic_data_sql.py

示例11: do_exec

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def do_exec(args):
            msg, sql = args
            with log_duration(msg):
                started = datetime.datetime.now()
                with engine.begin() as trans:
                    res = trans.execute(sql)
                    try:
                        logger.info(f"Ran", job=msg, result=res.fetchall())
                    except ResourceClosedError:
                        pass  # Nothing to do here 
开发者ID:Flowminder,项目名称:FlowKit,代码行数:12,代码来源:generate_synthetic_data.py

示例12: validate

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [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

示例13: test_graceful_fetch_on_non_rows

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def test_graceful_fetch_on_non_rows(self):
        """test that calling fetchone() etc. on a result that doesn't
        return rows fails gracefully.

        """

        # these proxies don't work with no cursor.description present.
        # so they don't apply to this test at the moment.
        # result.FullyBufferedCursorResult,
        # result.BufferedRowCursorResult,
        # result.BufferedColumnCursorResult

        users = self.tables.users

        conn = testing.db.connect()
        for meth in [
            lambda r: r.fetchone(),
            lambda r: r.fetchall(),
            lambda r: r.first(),
            lambda r: r.scalar(),
            lambda r: r.fetchmany(),
            lambda r: r._getter("user"),
            lambda r: r.keys(),
            lambda r: r.columns("user"),
            lambda r: r.cursor_strategy.fetchone(r, r.cursor),
        ]:
            trans = conn.begin()
            result = conn.execute(users.insert(), user_id=1)
            assert_raises_message(
                exc.ResourceClosedError,
                "This result object does not return rows. "
                "It has been closed automatically.",
                meth,
                result,
            )
            trans.rollback() 
开发者ID:sqlalchemy,项目名称:sqlalchemy,代码行数:38,代码来源:test_resultset.py

示例14: test_fetchone_til_end

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def test_fetchone_til_end(self, connection):
        result = connection.exec_driver_sql("select * from users")
        eq_(result.fetchone(), None)
        eq_(result.fetchone(), None)
        eq_(result.fetchone(), None)
        result.close()
        assert_raises_message(
            exc.ResourceClosedError,
            "This result object is closed.",
            result.fetchone,
        ) 
开发者ID:sqlalchemy,项目名称:sqlalchemy,代码行数:13,代码来源:test_resultset.py

示例15: _assert_result_closed

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ResourceClosedError [as 别名]
def _assert_result_closed(self, r):
        assert_raises_message(
            sa_exc.ResourceClosedError, "object is closed", r.fetchone
        )

        assert_raises_message(
            sa_exc.ResourceClosedError, "object is closed", r.fetchmany, 2
        )

        assert_raises_message(
            sa_exc.ResourceClosedError, "object is closed", r.fetchall
        ) 
开发者ID:sqlalchemy,项目名称:sqlalchemy,代码行数:14,代码来源:test_resultset.py


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