Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: connect method raises an exception when db problems #147

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions web/modeltr/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,18 +100,21 @@ def __init__(self, **kwargs):
#self._connect()

def _connect(self):
for i in range(Settings.app['retries']['db_connection']):
retries = Settings.app['retries']['db_connection']
for i in range(retries):
try:
self.async_mode = True if 'async_mode' in self._connection_params else False
self.client = psycopg2.connect(self._connection_params['dsn'], async_=int(self.async_mode))
if self.async_mode:
Connection.__wait_for_completion(self.client)
self.acursor = self.client.cursor()
self._last_usage_timestamp = time.time()
break
except psycopg2.OperationalError:
self.__logger.warning('Error connecting to the db server', exc_info=True)
time.sleep(0.1)
self._last_usage_timestamp = time.time()
else:
raise UnitDbConnectionError(f'Error connecting to the db server after {retries} tries')

def _refresh_conn_on_every_usage(self):
return "socket_reusability" in self._connection_params and \
Expand All @@ -129,7 +132,10 @@ def wait_for_completion(self):
@classmethod
def connect(cls, alias=DEFAULT_CONNECTION_NAME, **kwargs):
if alias not in cls.__connections:
cls.__connections[alias] = {"connection": cls(**kwargs), "args": kwargs}
logging.getLogger(__name__).debug("Creating connection object...")
connection = cls(**kwargs)
logging.getLogger(__name__).debug(f"Connection object created.")
cls.__connections[alias] = {"connection": connection, "args": kwargs}
return cls.use(alias)

@classmethod
Expand Down