Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def raiser():
raise OperationalError("foo", {}, psycopg2.OperationalError())
def wait_cb(conn):
"""A wait callback useful to allow eventlet to work with Psycopg."""
while 1:
if panic:
raise Exception('whatever')
state = conn.poll()
if state == extensions.POLL_OK:
break
elif state == extensions.POLL_READ:
trampoline(conn.fileno(), read=True)
elif state == extensions.POLL_WRITE:
trampoline(conn.fileno(), write=True)
else:
raise psycopg2.OperationalError(
"Bad result from poll: %r" % state)
def _wait(conn, timeout=None):
while 1:
try:
state = conn.poll()
if state == psycopg2.extensions.POLL_OK:
break
elif state == psycopg2.extensions.POLL_WRITE:
select.select([], [conn.fileno()], [], timeout)
elif state == psycopg2.extensions.POLL_READ:
select.select([conn.fileno()], [], [], timeout)
else:
raise psycopg2.OperationalError("poll() returned %s" % state)
except select.error:
raise psycopg2.OperationalError("select.error received")
while tries_N >= 0:
try:
curs = dbcon.cursor()
curs.execute(sql, data)
if fetch_N == 'all':
res = curs.fetchall()
elif fetch_N == 'one':
res = curs.fetchone()
elif fetch_N == 'none':
res = None
else:
raise Exception, "Bad value for fetch_N: %s" % fetch_N
curs.close()
dbcon.commit()
return (res,dbcon)
except (psycopg2.OperationalError, psycopg2.InterfaceError, psycopg2.InternalError), e:
lcfitlogger.error( "Error trying to execute query, reconnecting: \"%s\", \"%s\"." % (sql, e))
tries_N -= 1
time.sleep(2**tries_comp)
tries_comp += 1
try:
dbcon = psycopg2.connect(dbcon.dsn)
except Exception, e:
raise LcDataException, "Exception trying to connect: \"%s\"." % str(e)
lcfitlogger.warning( "Successfully reconnected, re-executed cursor.")
except:
raise
raise
def connection_error_types(self):
return psycopg2.InterfaceError, psycopg2.OperationalError
def _query(self, sql, *params):
"""We are always using the same cursor, therefore this method is not thread-safe!!!
You can call it from different threads only if you are holding explicit `AsyncExecutor` lock,
because the main thread is always holding this lock when running HA cycle."""
cursor = None
try:
cursor = self._cursor()
cursor.execute(sql, params)
return cursor
except psycopg2.Error as e:
if cursor and cursor.connection.closed == 0:
# When connected via unix socket, psycopg2 can't recoginze 'connection lost'
# and leaves `_cursor_holder.connection.closed == 0`, but psycopg2.OperationalError
# is still raised (what is correct). It doesn't make sense to continiue with existing
# connection and we will close it, to avoid its reuse by the `_cursor` method.
if isinstance(e, psycopg2.OperationalError):
self.close_connection()
else:
raise e
if self.state == 'restarting':
raise RetryFailedError('cluster is being restarted')
raise PostgresConnectionException('connection problems')
def _close(self):
"""Remove the connection from the event_loop and close it."""
# N.B. If connection contains uncommitted transaction the
# transaction will be discarded
if self._fileno is not None:
self._loop.remove_reader(self._fileno)
if self._writing:
self._writing = False
self._loop.remove_writer(self._fileno)
self._conn.close()
self.free_cursor()
if self._waiter is not None and not self._waiter.done():
self._waiter.set_exception(
psycopg2.OperationalError("Connection closed"))
global psycopg2
import psycopg2
except ImportError:
print(dedent("""
############################################################################################
Unable to import psycopg2 module to access database server.
Please install this module via 'conda install psycopg2' or 'pip install psycopg2'.
############################################################################################
"""))
raise
try:
pghost='redr.eng.hawaii.edu'
# note: the connection gets created when the module loads and never gets closed (until presumably python exits)
con = psycopg2.connect(database='switch', host=pghost) #, user='switch_user')
except psycopg2.OperationalError:
print(dedent("""
############################################################################################
Error while connecting to switch database on postgres server {server}.
Please ensure that the PGUSER environment variable is set with your postgres username
and there is a line like "*:*:*::" in ~/.pgpass (which should be chmod 0600)
or in %APPDATA%\postgresql\pgpass.conf (Windows).
See http://www.postgresql.org/docs/9.1/static/libpq-pgpass.html for more details.
############################################################################################
""".format(server=pghost)))
raise
return con.cursor()
_log = logging.getLogger(__name__)
default_app_config = 'django_dbconn_retry.DjangoIntegration'
pre_reconnect = Signal(providing_args=["dbwrapper"])
post_reconnect = Signal(providing_args=["dbwrapper"])
_operror_types = () # type: Union[Tuple[type], Tuple]
_operror_types += (django_db_utils.OperationalError,)
try:
import psycopg2
except ImportError:
pass
else:
_operror_types += (psycopg2.OperationalError,)
try:
import sqlite3
except ImportError:
pass
else:
_operror_types += (sqlite3.OperationalError,)
try:
import MySQLdb
except ImportError:
pass
else:
_operror_types += (MySQLdb.OperationalError,)