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


Python psycopg2.OperationalError方法代码示例

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


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

示例1: create_extension

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def create_extension(conn, extension_name, test=False):
    # The following error means that pglogical package is not installed into the operating system
    # ERROR:  could not open extension control file "/usr/share/postgresql/9.6/extension/pglogical.control":

    # The following error means that pglogical is installed but not configured correctly
    # ERROR:  pglogical is not in shared_preload_libraries
    cur = conn.cursor()
    try:
        cur.execute("CREATE EXTENSION IF NOT EXISTS %s" % extension_name)
        if not test:
            conn.commit()
    except psycopg2.InternalError as e:
        msg = str(e)
        if msg.find('shared_preload_libraries'):
            return 'InstalledNoSharedLibraries'
        return 'NotInstalled'
    except psycopg2.OperationalError:
        return 'NotInstalled'
    finally:
        if test:
            conn.rollback()
    return True 
开发者ID:rtshome,项目名称:pgrepup,代码行数:24,代码来源:database.py

示例2: pg_connection

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def pg_connection(self):
        """
        Return a connection to the db.
        """
        dbname = self.server_opts['db_name']
        user = self.server_opts['db_user']
        host = self.server_opts['db_host']
        password = self.server_opts['db_password']
        message = ''
        try:
            pg_conn = connect("dbname='%s' user='%s' host='%s' password='%s'"\
                % (dbname, user, host, password))
        except OperationalError:
            return None, 'Error : Server cannot connect to database'
        try:
            pg_conn.cursor().execute("""SELECT * FROM USERS""")
        except ProgrammingError:
            return None, 'Error : Server cannot connect to table in database'
        return pg_conn, message 
开发者ID:nbeguier,项目名称:cassh,代码行数:21,代码来源:tools.py

示例3: _gather_metrics

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def _gather_metrics(self):
        stats = {}
        try:
            for inject_method in self._select_stats_to_emit:
                stats = inject_method(stats)
        except psycopg2.OperationalError as exc:
            logging.exception("METRICS: error while gathering metrics")
            stats = {
                "health": {
                    "health": 0,
                    "diagnosis": "Database error: {}".format(str(exc)),
                }
            }
        except Exception:
            logging.exception("METRICS: error while gathering metrics")
            stats = {
                "health": {
                    "health": 4,
                    "diagnosis": "Unable to retrieve metrics",
                }
            }
        finally:
            return stats 
开发者ID:mendix,项目名称:cf-mendix-buildpack,代码行数:25,代码来源:metrics.py

示例4: test_invalid_login

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def test_invalid_login(self):
    """Tests if postgres server responds correctly to a invalid login attempt."""

    def postgresql_login():
      try:
        psycopg2.connect("postgres://scott:tiger@0.0.0.0:2504/")
      except psycopg2.OperationalError as e:
        return e
      return None

    options = {'enabled': 'True', 'port': 2504}
    postgresql_cap = postgresql.PostgreSQL(options, self.loop)

    server_coro = asyncio.start_server(
        postgresql_cap.handle_session, '0.0.0.0', 2504, loop=self.loop)
    self.server = self.loop.run_until_complete(server_coro)

    postgresql_task = self.loop.run_in_executor(None, postgresql_login)
    login_exception = self.loop.run_until_complete(postgresql_task)

    self.assertIsInstance(login_exception, psycopg2.OperationalError)
    self.assertEqual(
        str(login_exception),
        'FATAL:  password authentication failed for user "scott"\n') 
开发者ID:johnnykv,项目名称:heralding,代码行数:26,代码来源:test_postgresql.py

示例5: test_overwrite_schema

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def test_overwrite_schema(self):
        """
        Verifies option to overwrite connection schema
        """

        sql = "SELECT 1;"
        op = PostgresOperator(
            task_id='postgres_operator_test_schema_overwrite',
            sql=sql,
            dag=self.dag,
            autocommit=True,
            database="foobar",
        )

        from psycopg2 import OperationalError
        try:
            op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                   ignore_ti_state=True)
        except OperationalError as e:
            assert 'database "foobar" does not exist' in str(e) 
开发者ID:apache,项目名称:airflow,代码行数:22,代码来源:test_postgres.py

示例6: __init__

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def __init__(self):

        self.log = open('.database_actions.log', 'a')
        
        self.database_name  = "odds_data"
        self.matches_table  = "matches"
        
        self.odds_cols      = ['1', 'X', '2']
        self.timestamp_col  = "timestamp"
        
        self.teams          = teams()

        try:
            self.connect()

        except psycopg2.OperationalError:
            self.create_database()
            self.connect()

        self.cursor = self.connection.cursor(cursor_factory = psycopg2.extras.DictCursor)
        self.create_table() 
开发者ID:HaraldNordgren,项目名称:betting-crawler,代码行数:23,代码来源:database.py

示例7: connect_as_super_user

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def connect_as_super_user(db_name, conf):
    db_connection = None
    try:
        db_connection = psycopg2.connect(database=db_name)
        db_connection.autocommit = True
    except psycopg2.OperationalError:
        LOG.info("could not connect as local superuser with current user, credentials required")

    if not db_connection:
        superuser, password = query_user_for_superuser_credentials()
        db_connection = get_db_connection(db_name, superuser, password,
                                          host=conf['postgres']['host'],
                                          port=int(conf['postgres']['port']))

    if not db_connection or db_connection.closed:
        raise Exception("failed connecting the database: " + db_name)

    return db_connection 
开发者ID:spotify,项目名称:postgresql-metrics,代码行数:20,代码来源:prepare_db.py

示例8: connect

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def connect():
    """ Return a connection to the database"""
    try:
        if (not hasattr(connect, "conn") or connect.conn is None or connect.conn.closed != 0):
            cattr = dict(
                user=DB_USER,
                password=DB_PASSWORD,
                database=DB_NAME
            )
            if DB_HOST is not None:
                cattr.update(dict(
                            host=DB_HOST,
                            port=DB_PORT,
                            ))
            connect.conn = psycopg2.connect(**cattr)
            connect.conn.set_client_encoding('UTF8')
        return connect.conn
    except psycopg2.OperationalError as pgoe:
        logger.error(pgoe.message)
        raise
    except Exception:
        logger.error("Failed to connect to database.")
        raise 
开发者ID:tomslee,项目名称:airbnb-data-collection,代码行数:25,代码来源:schema_update.py

示例9: database_connection

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def database_connection(database_url):
    parsed = urlparse(database_url)
    user = parsed.username
    password = parsed.password
    host = parsed.hostname
    port = parsed.port
    database = parsed.path.strip('/')

    try:
        connection = psycopg2.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            database=database,
            cursor_factory=RealDictCursor)
    except psycopg2.OperationalError:
        raise UnableToConnectToDatabase
    connection.set_session(autocommit=True)

    return connection 
开发者ID:vokal,项目名称:pg-table-markdown,代码行数:23,代码来源:database.py

示例10: execute

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def execute(self, host, port='5432', user=None, password=None, database='postgres', ssl='disable', timeout='10'):

    try:
      with Timing() as timing:
        psycopg2.connect(host=host, port=int(port), user=user, password=password, database=database, sslmode=ssl, connect_timeout=int(timeout))

      code, mesg = '0', 'OK'

    except psycopg2.OperationalError as e:
      logger.debug('OperationalError: %s' % e)
      code, mesg = '1', str(e)[:-1]

    return self.Response(code, mesg, timing)

# }}}

# HTTP {{{ 
开发者ID:lanjelot,项目名称:patator,代码行数:19,代码来源:patator.py

示例11: wait_select_inter

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def wait_select_inter(conn):
    while 1:
        try:
            state = conn.poll()
            if state == POLL_OK:
                break
            elif state == POLL_READ:
                select([conn.fileno()], [], [])
            elif state == POLL_WRITE:
                select([], [conn.fileno()], [])
            else:
                raise conn.OperationalError(
                    "bad state from poll: %s" % state)
        except KeyboardInterrupt:
            conn.cancel()
            # the loop will be broken by a server error
            continue 
开发者ID:bgschiller,项目名称:postgres_kernel,代码行数:19,代码来源:kernel.py

示例12: database_status

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def database_status():
    try:
        psycopg2.connect(
            dbname=os.environ['DB_NAME'],
            user=os.environ['DB_USER'],
            password=os.environ['DB_PASS'],
            host=os.environ['DB_HOST'],
            port=os.environ['DB_PORT'],
            sslmode=os.environ['DB_SSLMODE'],
            sslcert=os.environ['DB_SSLCERT'],
            sslkey=os.environ['DB_SSLKEY'],
            sslrootcert=os.environ['DB_SSLROOTCERT'],
        )
    except psycopg2.OperationalError:
        time.sleep(3)
        return False
    else:
        return True 
开发者ID:openwisp,项目名称:docker-openwisp,代码行数:20,代码来源:services.py

示例13: connect_to_master

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def connect_to_master():
    citus_host    = environ.get('CITUS_HOST', 'master')
    postgres_pass = environ.get('POSTGRES_PASSWORD', '')
    postgres_user = environ.get('POSTGRES_USER', 'postgres')
    postgres_db   = environ.get('POSTGRES_DB', postgres_user)

    conn = None
    while conn is None:
        try:
            conn = psycopg2.connect("dbname=%s user=%s host=%s password=%s" %
                                    (postgres_db, postgres_user, citus_host, postgres_pass))
        except psycopg2.OperationalError as error:
            print("Could not connect to %s, trying again in 1 second" % citus_host)
            sleep(1)
        except (Exception, psycopg2.Error) as error:
            raise error
        
    conn.autocommit = True

    print("connected to %s" % citus_host, file=stderr)

    return conn

# main logic loop for the manager 
开发者ID:citusdata,项目名称:membership-manager,代码行数:26,代码来源:manager.py

示例14: wait_on_postgres

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def wait_on_postgres(retries=5, migrate=True):
    """Block until Postgres is ready (optionally, run any migrations)

    Shamelessly appropriated from https://github.com/agconti/wait-for-postgres
    """
    dsn = os.environ.get('DATABASE_URL')

    @retry(retries, exceptions=(psycopg2.OperationalError,))
    def wait():
        con = psycopg2.connect(**psycopg2.extensions.parse_dsn(dsn))
        con.close()
        log.info('Postgres is ready!')

    wait()
    if migrate:
        log.info('Running database migrations, if any')
        with application.app_context():
            flask_migrate.upgrade(directory=MIGRATION_DIR) 
开发者ID:betterlife,项目名称:betterlifepsi,代码行数:20,代码来源:cli.py

示例15: init_db_connection

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import OperationalError [as 别名]
def init_db_connection(connect_str):
    """Initializes database connection using the specified Flask app.

    Configuration file must contain `SQLALCHEMY_DATABASE_URI` key. See
    https://pythonhosted.org/Flask-SQLAlchemy/config.html#configuration-keys
    for more info.
    """
    global engine
    while True:
        try:
            engine = create_engine(connect_str, poolclass=NullPool)
            print("Connection to db established!")
            break
        except psycopg2.OperationalError as e:
            print("Couldn't establish connection to db: {}".format(str(e)))
            print("Sleeping 2 seconds and trying again...")
            time.sleep(2) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:19,代码来源:__init__.py


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