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


Python exc.OperationalError方法代码示例

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


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

示例1: main

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def main(args, env):
    global Session

    if args.verbose >= 1:
        app.config['DEBUG'] = True
    sys.stderr.write("connecting to DB server {:s}\n".format(args.db))
    connection_succeeded = False
    while not connection_succeeded:
        try:
            engine = create_engine(args.db)
            Session = sessionmaker(bind = engine)
            Base.metadata.create_all(engine)
            sys.stderr.write("connection succeeded!\n")
            connection_succeeded = True
            app.run(debug = args.verbose >= 1, host = "0.0.0.0", port = 80)
        except OperationalError as err:
            if "Connection refused" in str(err):
                connection_succeeded = False
                time.sleep(10)
            else:
                raise 
开发者ID:Cisco-Talos,项目名称:BASS,代码行数:23,代码来源:server.py

示例2: execute_query

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def execute_query(instance: PluginInstance, sql_query: Union[str, Query],
                  rows_as_dict: bool = False) -> web.Response:
    try:
        res: ResultProxy = instance.inst_db.execute(sql_query)
    except exc.IntegrityError as e:
        return resp.sql_integrity_error(e, sql_query)
    except exc.OperationalError as e:
        return resp.sql_operational_error(e, sql_query)
    data = {
        "ok": True,
        "query": str(sql_query),
    }
    if res.returns_rows:
        row: RowProxy
        data["rows"] = [({key: check_type(value) for key, value in row.items()}
                         if rows_as_dict
                         else [check_type(value) for value in row])
                        for row in res]
        data["columns"] = res.keys()
    else:
        data["rowcount"] = res.rowcount
    if res.is_insert:
        data["inserted_primary_key"] = res.inserted_primary_key
    return web.json_response(data) 
开发者ID:maubot,项目名称:maubot,代码行数:26,代码来源:instance_database.py

示例3: run

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def run(self):
        while True:
            i = self.queue.get()
            if i == 'dummy':
                self.queue.task_done()
                break
            if i['task'] == 'add_format':
                cur_book = self.session.query(Books).filter(Books.id == i['id']).first()
                cur_book.data.append(i['format'])
                try:
                    # db.session.merge(cur_book)
                    self.session.commit()
                except OperationalError as e:
                    self.session.rollback()
                    self.log.error("Database error: %s", e)
                    # self._handleError(_(u"Database error: %(error)s.", error=e))
                    # return
            self.queue.task_done() 
开发者ID:janeczku,项目名称:calibre-web,代码行数:20,代码来源:db.py

示例4: _pg_create_db

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def _pg_create_db(cfg, eng, ident):
    with eng.connect().execution_options(
            isolation_level="AUTOCOMMIT") as conn:
        try:
            _pg_drop_db(cfg, conn, ident)
        except Exception:
            pass
        currentdb = conn.scalar("select current_database()")
        for attempt in range(3):
            try:
                conn.execute(
                    "CREATE DATABASE %s TEMPLATE %s" % (ident, currentdb))
            except exc.OperationalError as err:
                if attempt != 2 and "accessed by other users" in str(err):
                    time.sleep(.2)
                    continue
                else:
                    raise
            else:
                break 
开发者ID:jpush,项目名称:jbox,代码行数:22,代码来源:provision.py

示例5: mysql_ping_listener

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

示例6: upgrade

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def upgrade():
    try:
        op.create_table('eventhandlercondition',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('eventhandler_id', sa.Integer(), nullable=True),
        sa.Column('Key', sa.Unicode(length=255), nullable=False),
        sa.Column('Value', sa.Unicode(length=2000), nullable=True),
        sa.Column('comparator', sa.Unicode(length=255), nullable=True),
        sa.ForeignKeyConstraint(['eventhandler_id'], ['eventhandler.id'], ),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('eventhandler_id', 'Key', name='ehcix_1')
        )
    except (OperationalError, ProgrammingError, InternalError) as exx:
        if "duplicate column name" in str(exx.orig).lower():
            print("Good. Table eventhandlercondition already exists.")
        else:
            print("Table already exists")
            print(exx)

    except Exception as exx:
        print("Could not add Table eventhandlercondition")
        print (exx) 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:24,代码来源:3ae3c668f444_.py

示例7: upgrade

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def upgrade():
    try:
        op.create_table('passwordreset',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('recoverycode', sa.Unicode(length=255), nullable=False),
        sa.Column('username', sa.Unicode(length=64), nullable=False),
        sa.Column('realm', sa.Unicode(length=64), nullable=False),
        sa.Column('resolver', sa.Unicode(length=64), nullable=True),
        sa.Column('email', sa.Unicode(length=255), nullable=True),
        sa.Column('timestamp', sa.DateTime(), nullable=True),
        sa.Column('expiration', sa.DateTime(), nullable=True),
        sa.PrimaryKeyConstraint('id')
        )
        op.create_index(op.f('ix_passwordreset_realm'), 'passwordreset',
                        ['realm'], unique=False)
        op.create_index(op.f('ix_passwordreset_username'), 'passwordreset',
                        ['username'], unique=False)
    except (OperationalError, ProgrammingError, InternalError) as exx:
        if "duplicate column name" in str(exx.orig).lower():
            print("Good. Table passwordreset already exists.")
        else:
            print(exx)
    except Exception as exx:
        print ("Could not add table 'passwordreset'")
        print (exx) 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:27,代码来源:4023571658f8_.py

示例8: upgrade

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def upgrade():
    try:
        op.add_column('token', sa.Column('revoked', sa.Boolean(),
                                         default=False))
    except (OperationalError, ProgrammingError, InternalError) as exx:
        if "duplicate column name" in str(exx.orig).lower():
            print("Good. Column revoked already exists.")
        else:
            print(exx)
    except Exception as exx:
        print ("Could not add column 'revoked' to table 'token'")
        print (exx)

    try:
        op.add_column('token', sa.Column('locked', sa.Boolean(),
                                         default=False))
    except (OperationalError, ProgrammingError)  as exx:
        if "duplicate column name" in str(exx.orig).lower():
            print("Good. Column locked already exists.")
        else:
            print(exx)
    except Exception as exx:
        print ("Could not add column 'locked' to table 'token'")
        print (exx) 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:26,代码来源:20969b4cbf06_.py

示例9: upgrade

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def upgrade():
    try:
        op.create_table('radiusserver',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('identifier', sa.Unicode(length=255), nullable=False),
        sa.Column('server', sa.Unicode(length=255), nullable=False),
        sa.Column('port', sa.Integer(), nullable=True),
        sa.Column('secret', sa.Unicode(length=255), nullable=True),
        sa.Column('description', sa.Unicode(length=2000), nullable=True),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('identifier')
        )
    except (OperationalError, ProgrammingError, InternalError) as exx:
        if "duplicate column name" in str(exx.orig).lower():
            print("Good. Table 'radiusserver' already exists.")
        else:
            print(exx)
    except Exception as exx:
        print ("Could not add table 'radiusserver'")
        print (exx) 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:22,代码来源:449903fb6e35_.py

示例10: to_database

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def to_database(
    graph,
    manager: Optional[Manager] = None,
    use_tqdm: bool = True,
):
    """Store a graph in a database.

    :param BELGraph graph: A BEL graph
    :return: If successful, returns the network object from the database.
    :rtype: Optional[Network]
    """
    if manager is None:
        manager = Manager()

    try:
        return manager.insert_graph(graph, use_tqdm=use_tqdm)
    except (IntegrityError, OperationalError):
        manager.session.rollback()
        logger.exception('Error storing graph')
    except Exception as e:
        manager.session.rollback()
        raise e 
开发者ID:pybel,项目名称:pybel,代码行数:24,代码来源:database_io.py

示例11: __init__

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def __init__(self, db_str="sqlite:///:memory:"):
        if sqlalchemy is None:
            raise ImportError("Cannot import SQLAlchemy. Please install SQLAlchemy before using %s."
                              % self.__class__.__name__)

        # ORM declarations
        engine = create_engine(db_str)

        # create table
        try:
            Base.metadata.create_all(engine, checkfirst=True)
        except OperationalError:
            # table already exists
            pass

        self.Session = sessionmaker(bind=engine) 
开发者ID:angr,项目名称:angr,代码行数:18,代码来源:spiller.py

示例12: test_raises_without_using_transaction_retry

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def test_raises_without_using_transaction_retry(
    toxiproxy_db_session, toxiproxy, disconnect
):
    if not toxiproxy:
        pytest.skip('Toxiproxy not installed')

    def get_model_count():
        return toxiproxy_db_session.query(ExampleModel).count()

    toxiproxy_db_session.add(ExampleModel(data='hello1'))
    toxiproxy_db_session.add(ExampleModel(data='hello2'))
    toxiproxy_db_session.commit()

    disconnect(reconnect=True)

    with pytest.raises(OperationalError):
        get_model_count() 
开发者ID:nameko,项目名称:nameko-sqlalchemy,代码行数:19,代码来源:test_transaction_retry.py

示例13: __init__

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def __init__(self):
        if __project__.name is None:
            DB_NAME = 'default.db'
            db_path = path.join(__project__.get_path(), DB_NAME)
        else:
            DB_NAME = __project__.name + '.db'
            db_path = path.join(__project__.get_path(), DB_NAME)

        # Connect to Postgres DB
        self.engine = create_engine('postgresql+psycopg2://{0}:{1}!@localhost/cirtkit'.format(DB_USER, DB_PASSWD))

        self.engine.echo = False
        self.engine.pool_timeout = 60

        try:
            Base.metadata.create_all(self.engine)
        except OperationalError:
            # Connect to local SQLite DB if cannot connect to Postgres
            self.engine = create_engine('sqlite:///{0}'.format(db_path), poolclass=NullPool)
            Base.metadata.create_all(self.engine)

        self.Session = sessionmaker(bind=self.engine) 
开发者ID:opensourcesec,项目名称:CIRTKit,代码行数:24,代码来源:database.py

示例14: _retry_on_deadlock

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def _retry_on_deadlock(fn):
    """Decorator to retry a DB API call if Deadlock was received."""
    lock_messages_error = ['Deadlock found', 'Lock wait timeout exceeded']

    @wraps(fn)
    def wrapped(*args, **kwargs):
        while True:
            try:
                return fn(*args, **kwargs)
            except dbexc.OperationalError as e:
                if any(msg in e.message for msg in lock_messages_error):
                    # msg = ("Deadlock detected when running %s Retrying..." %
                    #        (fn.__name__))
                    # rc_util.syslogout(msg, syslog.LOG_WARNING)
                    # Retry!
                    time.sleep(0.5)
                    continue
    return wrapped 
开发者ID:ntt-sic,项目名称:masakari,代码行数:20,代码来源:api.py

示例15: on_get

# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import OperationalError [as 别名]
def on_get(self, req, resp):
        # TODO pull status args out of request
        engine = req.params.get('engine')
        type = req.params.get('type', '')
        try:
            gen = AirflowScheduler.query(engine)
        except OperationalError:
            logging.debug('Scheduler offline, using fake scheduler query')
            gen = AirflowScheduler.fakequery(engine)
        if type == 'jobs':
            ret = gen['jobs']
        elif type == 'reports':
            ret = gen['reports']
        else:
            ret = gen

        resp.content_type = 'application/json'
        resp.body = json.dumps(ret) 
开发者ID:timkpaine,项目名称:paperboy,代码行数:20,代码来源:remote_airflow.py


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