How to use the pg8000.connect function in pg8000

To help you get started, we’ve selected a few pg8000 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mfenniak / pg8000 / tests / test_connection.py View on Github external
def testBrokenPipe(self):
        db1 = pg8000.connect(**db_connect)
        db2 = pg8000.connect(**db_connect)

        try:
            cur1 = db1.cursor()
            cur2 = db2.cursor()

            cur1.execute("select pg_backend_pid()")
            pid1 = cur1.fetchone()[0]

            cur2.execute("select pg_terminate_backend(%s)", (pid1,))
            try:
                cur1.execute("select 1")
            except Exception as e:
                self.assertTrue(isinstance(e, (socket.error, struct.error)))

            cur2.close()
github OperationCode / operationcode_pyback / tests / posgresql.py View on Github external
def poststart(self):
        with closing(pg8000.connect(**self.dsn(database='postgres'))) as conn:
            conn.autocommit = True
            with closing(conn.cursor()) as cursor:
                cursor.execute("SELECT COUNT(*) FROM pg_database WHERE datname='test'")
                if cursor.fetchone()[0] <= 0:
                    cursor.execute('CREATE DATABASE test')
github mfenniak / pg8000 / tests / test_dbapi.py View on Github external
def setUp(self):
        self.db = pg8000.connect(**db_connect)

        # Neither Windows nor Jython 2.5.3 have a time.tzset() so skip
        if hasattr(time, 'tzset'):
            os.environ['TZ'] = "UTC"
            time.tzset()
            self.HAS_TZSET = True
        else:
            self.HAS_TZSET = False

        try:
            c = self.db.cursor()
            try:
                c = self.db.cursor()
                c.execute("DROP TABLE t1")
            except pg8000.DatabaseError:
                e = exc_info()[1]
github tk0miya / testing.postgresql / tests / test_postgresql.py View on Github external
self.assertEqual('127.0.0.1', params['host'])
            self.assertEqual(pgsql.settings['port'], params['port'])
            self.assertEqual('postgres', params['user'])

            # connect to postgresql (w/ psycopg2)
            conn = psycopg2.connect(**pgsql.dsn())
            self.assertIsNotNone(conn)
            self.assertRegexpMatches(pgsql.read_bootlog(), 'is ready to accept connections')
            conn.close()

            # connect to postgresql (w/ sqlalchemy)
            engine = sqlalchemy.create_engine(pgsql.url())
            self.assertIsNotNone(engine)

            # connect to postgresql (w/ pg8000)
            conn = pg8000.connect(**pgsql.dsn())
            self.assertIsNotNone(conn)
            self.assertRegexpMatches(pgsql.read_bootlog(), 'is ready to accept connections')
            conn.close()
        finally:
            # shutting down
            pid = pgsql.server_pid
            self.assertTrue(pgsql.is_alive())

            pgsql.stop()
            sleep(1)

            self.assertFalse(pgsql.is_alive())
            with self.assertRaises(OSError):
                os.kill(pid, 0)  # process is down
github mengfeng / zjobs / run_housekeeping.py View on Github external
def remove_old_records():
    conn = dbi.connect(host=config.DB_HOST, database=config.DATABASE, user=config.DB_USER, password=config.DB_PASSWORD)
    c = conn.cursor()
    c.execute("DELETE FROM CRAWLED_JOBS WHERE publish_date < NOW() - INTERVAL '" + str(config.HOUSEKEEPING_RECORD_ORDLER_THAN) +" days'")
    conn.commit()
    conn.close()
github mengfeng / zjobs / app / run_crawler.py View on Github external
def refresh_database():
    #conn = dbi.connect(config.DB_FILE)
    conn = dbi.connect(host=config.DB_HOST, database=config.DATABASE, user=config.DB_USER, password=config.DB_PASSWORD)
    c = conn.cursor()
    c.execute('DELETE FROM CRAWLED_JOBS')
    conn.commit()
    conn.close()
github serverdensity / sd-agent / checks.d / postgres.py View on Github external
def get_connection(self, key, host, port, user, password, dbname, ssl, use_cached=True):
        "Get and memoize connections to instances"
        if key in self.dbs and use_cached:
            return self.dbs[key]

        elif host != "" and user != "":
            try:
                if host == 'localhost' and password == '':
                    # Use ident method
                    connection = pg.connect("user=%s dbname=%s" % (user, dbname))
                elif port != '':
                    connection = pg.connect(host=host, port=port, user=user,
                        password=password, database=dbname, ssl=ssl)
                else:
                    connection = pg.connect(host=host, user=user, password=password,
                        database=dbname, ssl=ssl)
            except Exception as e:
                message = u'Error establishing postgres connection: %s' % (str(e))
                service_check_tags = self._get_service_check_tags(host, port, dbname)
                self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
                    tags=service_check_tags, message=message)
                raise
        else:
            if not host:
                raise CheckException("Please specify a Postgres host to connect to.")
            elif not user:
                raise CheckException("Please specify a user to connect to Postgres as.")

        self.dbs[key] = connection
        return connection
github devpi / devpi / postgresql / devpi_postgresql / main.py View on Github external
def get_connection(self, closing=True, write=False):
        sqlconn = pg8000.connect(
            user=self.user,
            database=self.database,
            host=self.host,
            port=int(self.port),
            unix_sock=self.unix_sock,
            password=self.password,
            ssl=self.ssl_opts,
            timeout=60)
        sqlconn.text_factory = bytes
        conn = Connection(sqlconn, self)
        if write:
            q = 'SELECT pg_advisory_xact_lock(1);'
            c = conn._sqlconn.cursor()
            c.execute(q)
        if closing:
            return contextlib.closing(conn)
github scalyr / scalyr-agent-2 / scalyr_agent / builtin_monitors / postgres_monitor.py View on Github external
def connect(self):
        try:
            conn = pg8000.connect(user = self._user, host = self._host, port = self._port,
                                  database = self._database, password = self._password)
            self._db = conn
            self._cursor = self._db.cursor()
            self._gather_db_information()                                                   
        except pg8000.Error, me:
            self._db = None
            self._cursor = None
            self._logger.error("Database connect failed: %s" % me)
        except Exception, ex:
            self._logger.error("Exception trying to connect occured:  %s" % ex)
            raise Exception("Exception trying to connect:  %s" % ex)