Python psycopg2 模块,OperationalError() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用psycopg2.OperationalError()。
def apply_migration(self, name, statements, fake=False):
import psycopg2
connection = self.get_connection()
with connection.cursor() as cursor:
try:
if not fake and statements.strip():
cursor.execute(statements)
except (
psycopg2.OperationalError,
psycopg2.ProgrammingError) as e:
connection.rollback()
print(e.message)
from sqlibrist.helpers import ApplyMigrationFailed
raise ApplyMigrationFailed
else:
cursor.execute('INSERT INTO sqlibrist.migrations '
'(migration) VALUES (%s);',
[name.split('/')[-1]])
connection.commit()
def install_server(db):
db.socket = str(db.installation_dir.join('MysqL.sock'))
db.installation_dir.ensure_dir('tmp')
mycnf = db.installation_dir.join('my.cnf')
mycnf.write('[MysqLd]\n'
'datadir=%(installation_dir)s\n'
#'log\n'
#'log-error\n'
'skip-networking\n'
'socket=MysqL.sock\n'
'pid-file=MysqLd.pid\n'
'tmpdir=tmp\n' % { 'installation_dir': db.installation_dir })
subprocess.check_call(['MysqL_install_db', '--defaults-file=' + str(mycnf)])
server = subprocess.Popen(['MysqLd', '--defaults-file=' + str(mycnf)])
import time, MysqLdb
tries = 30
for t in range(tries):
try:
with db.root() as cur:
cur.execute("CREATE USER 'abe'@'localhost' IDENTIFIED BY 'Bitcoin'")
return server
except MysqLdb.OperationalError as e:
if t+1 == tries:
raise e
time.sleep(1)
def install_server(db):
db.bindir = subprocess.Popen(['pg_config', '--bindir'], stdout=subprocess.PIPE).communicate()[0].rstrip()
subprocess.check_call([
os.path.join(db.bindir, 'initdb'),
'-D', str(db.installation_dir),
'-U', 'postgres'])
server = subprocess.Popen([
os.path.join(db.bindir, 'postgres'),
'-c', 'listen_addresses=', 'unix_socket_directory=.'])
import time, psycopg2
tries = 30
for t in range(tries):
try:
with db.root() as cur:
cur.execute("COMMIT") # XXX
cur.execute("CREATE USER abe UNENCRYPTED PASSWORD 'Bitcoin'")
cur.execute("COMMIT")
return server
except psycopg2.OperationalError as e:
if t+1 == tries:
raise e
time.sleep(1)
def get_current_user(self):
"""Current user"""
session = await get_session(self.request)
email = session.get('email', None)
if email is None:
return None
try:
user = await settings.manager.get(
User
.select()
.where(User.email == email))
except (User.DoesNotExist, psycopg2.OperationalError,
peewee.IntegrityError, peewee.ProgrammingError):
return None
if not (user.active and user.superuser):
return None
return email
def unapply_migration(self, fake=False):
import psycopg2
connection = self.get_connection()
with connection.cursor() as cursor:
try:
if not fake:
cursor.execute(statements)
except (
psycopg2.OperationalError,
psycopg2.ProgrammingError) as e:
connection.rollback()
print(e.message)
from sqlibrist.helpers import ApplyMigrationFailed
raise ApplyMigrationFailed
else:
cursor.execute('DELETE FROM sqlibrist.migrations '
'WHERE migration = (%s); ', [name])
connection.commit()
def apply_migration(self, fake=False):
import MysqLdb
connection = self.get_connection()
cursor = connection.cursor()
try:
if not fake and statements.strip():
cursor.execute(statements)
except (MysqLdb.OperationalError, MysqLdb.ProgrammingError) as e:
print('\n'.join(map(str, e.args)))
from sqlibrist.helpers import ApplyMigrationFailed
raise ApplyMigrationFailed
else:
cursor.execute('INSERT INTO sqlibrist_migrations '
'(migration) VALUES (%s);',
[name.split('/')[-1]])
def unapply_migration(self, fake=False):
import MysqLdb
connection = self.get_connection()
cursor = connection.cursor()
try:
if not fake:
cursor.execute(statements)
except (MysqLdb.OperationalError, e.args)))
from sqlibrist.helpers import ApplyMigrationFailed
raise ApplyMigrationFailed
else:
cursor.execute('DELETE FROM sqlibrist_migrations '
'WHERE migration = (%s); ', [name])
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, self.conn.cursor,
scrollable=False)
curs = self.conn.cursor()
curs.execute("create table scrollable (data int)")
curs.executemany("insert into scrollable values (%s)",
[(i,) for i in range(100)])
curs.close()
curs = self.conn.cursor("S") # default scrollability
curs.execute("select * from scrollable")
self.assertEqual(curs.scrollable, None)
curs.scroll(2)
try:
curs.scroll(-1)
except psycopg2.OperationalError:
return self.skipTest("can't evaluate non-scrollable cursor")
curs.close()
curs = self.conn.cursor("S", scrollable=False)
self.assertEqual(curs.scrollable, False)
curs.execute("select * from scrollable")
curs.scroll(2)
self.assertRaises(psycopg2.OperationalError, curs.scroll, -1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def uriDatabaseConnect(self, uri):
"""Create a connection from a uri and return a cursor of it."""
conninfo = uri.connectionInfo()
conn = None
cur = None
ok = False
while not conn:
try:
conn = psycopg2.connect(uri.connectionInfo())
cur = conn.cursor()
except psycopg2.OperationalError as e:
(ok, user, passwd) = QgsCredentials.instance().get(conninfo, uri.username(), uri.password())
if not ok:
break
if not conn:
QMessageBox.warning(self.iface.mainWindow(), "Connection Error", "Could not connect to Postgresql database - check connection info")
if ok:
QgsCredentials.instance().put(conninfo, passwd)
return cur
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def tearDown(self):
if self.tmpdir:
shutil.rmtree(self.tmpdir, "n")
except psycopg2.OperationalError:
pass
else:
lo.unlink()
ConnectingTestCase.tearDown(self)
def run(self):
"""Runs method that performs all the real work."""
self.con = None
try:
con_info = self.con_info
self.con = db.get_con(con_info)
if not db.chck_nofa_tbls(self.con):
self._open_con_dlg(con_info)
except psycopg2.OperationalError:
self._open_con_dlg(con_info)
if not self.con:
return
self.ins_mw.prep()
self.ins_mw.show()
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, e:
if e.pgcode != psycopg2.errorcodes.ADMIN_SHUTDOWN:
raise
except psycopg2.DatabaseError, e:
# curIoUsly when disconnected in green mode we get a DatabaseError
# without pgcode.
if e.pgcode is not None:
raise
self.assertEqual(conn.closed, 2)
conn.close()
self.assertEqual(conn.closed, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError,
[ (i,) for i in range(100) ])
curs.close()
curs = self.conn.cursor("S") # default scrollability
curs.execute("select * from scrollable")
self.assertEqual(curs.scrollable, -1)
def tearDown(self):
if self.tmpdir:
shutil.rmtree(self.tmpdir, "n")
except psycopg2.OperationalError:
pass
else:
lo.unlink()
ConnectingTestCase.tearDown(self)
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def tearDown(self):
if self.tmpdir:
shutil.rmtree(self.tmpdir, "n")
except psycopg2.OperationalError:
pass
else:
lo.unlink()
ConnectingTestCase.tearDown(self)
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def tearDown(self):
if self.tmpdir:
shutil.rmtree(self.tmpdir, "n")
except psycopg2.OperationalError:
pass
else:
lo.unlink()
ConnectingTestCase.tearDown(self)
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def tearDown(self):
if self.tmpdir:
shutil.rmtree(self.tmpdir, "n")
except psycopg2.OperationalError:
pass
else:
lo.unlink()
ConnectingTestCase.tearDown(self)
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def tearDown(self):
if self.tmpdir:
shutil.rmtree(self.tmpdir, "n")
except psycopg2.OperationalError:
pass
else:
lo.unlink()
ConnectingTestCase.tearDown(self)
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def tearDown(self):
if self.tmpdir:
shutil.rmtree(self.tmpdir, "n")
except psycopg2.OperationalError:
pass
else:
lo.unlink()
ConnectingTestCase.tearDown(self)
def filter_class_ids():
"""Wrapper to avoid importing storage_plugin_manager at module scope (it
requires DB to construct itself) so that this module can be imported
for e.g. building docs without a database.
Return a list of storage resource class IDs which are valid for display (i.e.
those for which we have a plugin available in this process)
"""
from psycopg2 import OperationalError
from django.db.utils import DatabaseError
try:
from chroma_core.lib.storage_plugin.manager import storage_plugin_manager
return storage_plugin_manager.resource_class_id_to_class.keys()
except (OperationalError, DatabaseError):
# OperationalError if the DB server can't be contacted
# DatabaseError if the DB exists but isn't populated
return []
def repl_connect(self, **kwargs):
"""Return a connection set up for replication
The connection is on "PSYcopG2_TEST_REPL_DSN" unless overridden by
a *dsn* kwarg.
Should raise a skip test if not available,but guard for None on
old Python versions.
"""
if 'dsn' not in kwargs:
kwargs['dsn'] = repl_dsn
import psycopg2
try:
conn = self.connect(**kwargs)
except psycopg2.OperationalError, e:
return self.skipTest("replication db not configured: %s" % e)
conn.autocommit = True
return conn
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def tearDown(self):
if self.tmpdir:
shutil.rmtree(self.tmpdir, "n")
except psycopg2.OperationalError:
pass
else:
lo.unlink()
ConnectingTestCase.tearDown(self)
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
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()
def _connect(self, database, encoding=None, **kwargs):
"""Attempt to connect to the DB.
In case it's not available,'fail over' to the back-up stand-by DB and propagete
it to the master DB.
"""
try:
return super()._connect(database, encoding=encoding, **kwargs)
except OperationalError as ex:
logging.info("Failing over to %s", self.failover_host)
if "Could not connect to server" in ex.args[0] or "Could not translate host name" in ex.args[0]:
kwargs["host"] = self.failover_host
conn = super()._connect(database, **kwargs)
with conn.cursor() as cr:
cr.execute("SELECT promote_standby();")
self.connect_kwargs[
"host"], self.failover_host = self.failover_host, self.connect_kwargs["host"]
return conn
else:
raise ex
def test_cleanup_on_badconn_close(self):
# ticket #148
conn = self.conn
cur = conn.cursor()
try:
cur.execute("select pg_terminate_backend(pg_backend_pid())")
except psycopg2.OperationalError, 1)
def test_not_scrollable(self):
self.assertRaises(psycopg2.ProgrammingError, -1)
def tearDown(self):
if self.tmpdir:
shutil.rmtree(self.tmpdir, "n")
except psycopg2.OperationalError:
pass
else:
lo.unlink()
ConnectingTestCase.tearDown(self)
def postgres_connection(connection_string, retry_counter=1):
try:
connection = psycopg2.connect(connection_string)
except psycopg2.OperationalError as e:
if retry_counter > LIMIT_RETRIES:
logging.error("CAN'T CONNECT TO POSTGRES")
logging.error("Check your connection settings.")
logging.error("Or increase (in docker-compose.yml):")
logging.error(
"TAIGA_DB_CHECK_SLEEP_INTERVAL / TAIGA_DB_CHECK_LIMIT_RETRIES."
)
logging.error("Exception messsage: {}".format(e))
sys.exit(1)
else:
logging.warning("Can't connect to Postgres. Will try again...")
time.sleep(SLEEP_INTERVAL)
retry_counter += 1
return postgres_connection(connection_string, retry_counter)
return connection
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。