Skip to content

Commit 32d9696

Browse files
Kamal Sai DevarapalliKamal Sai Devarapalli
authored andcommitted
Fix: Resolve pylint issues in db_conn_manager.py
- Remove unused Optional import from typing - Remove duplicate error logging (5 instances) - Fix return type annotation for bind_db_app() method - Split all long lines to comply with 79 character limit (20+ instances) - Improve exception handling with specific exceptions - Fix typo: 'doesn't exists' -> 'doesn't exist' - Extract variables to reduce line length in display_pool_info
1 parent 35e81ea commit 32d9696

File tree

1 file changed

+94
-68
lines changed

1 file changed

+94
-68
lines changed

common/pyportal_common/db_handlers/db_conn_manager.py

Lines changed: 94 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import sys
44
import time
5-
from typing import Union, Optional
5+
from typing import Union
66
import flask
77
import sqlalchemy.exc
88
from flask_sqlalchemy import SQLAlchemy
@@ -18,7 +18,8 @@ class DataBaseConnectionHandler:
1818

1919
def __init__(self, **kwargs) -> None:
2020
"""
21-
Initializes the DataBaseHandler object with database connection parameters.
21+
Initialize the DataBaseHandler object with database connection
22+
parameters.
2223
2324
Args:
2425
logger_instance: Logger instance for logging.
@@ -64,14 +65,20 @@ def _prepare_database_uri(self) -> Union[str, None]:
6465
return self._database_uri
6566
else:
6667
self._database_uri = (
67-
f"{self.db_driver}://{self.db_user}:{quote_plus(self._db_password)}@{self._db_ip_address}:{str(self.db_port)}"
68+
f"{self.db_driver}://{self.db_user}:"
69+
f"{quote_plus(self._db_password)}@"
70+
f"{self._db_ip_address}:{str(self.db_port)}"
6871
f"/{self.db_name}"
6972
)
70-
self.cmn_logger.info(f"Prepared DatabaseURI for Service :: [{self.cmn_logger.name}] - {self._database_uri}")
73+
self.cmn_logger.info(
74+
f"Prepared DatabaseURI for Service :: "
75+
f"[{self.cmn_logger.name}] - {self._database_uri}"
76+
)
7177
return self._database_uri
72-
except Exception as ex:
78+
except (ValueError, AttributeError) as ex:
7379
self.cmn_logger.error(
74-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
80+
f"Error occurred :: {ex}\tLine No:: "
81+
f"{sys.exc_info()[2].tb_lineno}"
7582
)
7683
return self._database_uri
7784

@@ -83,22 +90,24 @@ def create_db_engine_for_service(
8390
while _retries < self._max_retries:
8491
try:
8592
self.cmn_logger.info(
86-
f"Creating DB-Engine using DatabaseURI for Service :: [{self.cmn_logger.name}]"
93+
f"Creating DB-Engine using DatabaseURI for "
94+
f"Service :: [{self.cmn_logger.name}]"
95+
)
96+
app_instance.config["SQLALCHEMY_DATABASE_URI"] = (
97+
self._prepare_database_uri()
8798
)
88-
app_instance.config["SQLALCHEMY_DATABASE_URI"] = self._prepare_database_uri()
8999
db_engine: Engine = create_engine(
90100
app_instance.config["SQLALCHEMY_DATABASE_URI"]
91101
)
92102
self.cmn_logger.info(
93-
f"Created DB-Engine using DatabaseURI for Service :: [{db_engine}]"
103+
f"Created DB-Engine using DatabaseURI for "
104+
f"Service :: [{db_engine}]"
94105
)
95106
return db_engine, True
96-
except Exception as ex:
97-
self.cmn_logger.error(
98-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
99-
)
107+
except (sqlalchemy.exc.SQLAlchemyError, ValueError) as ex:
100108
self.cmn_logger.error(
101-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
109+
f"Error occurred :: {ex}\tLine No:: "
110+
f"{sys.exc_info()[2].tb_lineno}"
102111
)
103112
_retries += 1
104113
if _retries < self._max_retries:
@@ -108,160 +117,173 @@ def create_db_engine_for_service(
108117
time.sleep(self._retry_interval)
109118
else:
110119
return None, False
111-
except Exception as ex:
120+
except (sqlalchemy.exc.SQLAlchemyError, ValueError) as ex:
112121
self.cmn_logger.error(
113-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
122+
f"Error occurred :: {ex}\tLine No:: "
123+
f"{sys.exc_info()[2].tb_lineno}"
114124
)
115125
return None, False
116126

117127
def create_database_for_service(self) -> Union[bool, None]:
118128
try:
119129
if not database_exists(self._database_uri):
120130
self.cmn_logger.info(
121-
f"Database doesn't exists :: {self._database_uri.split('/')[-1]}"
131+
f"Database doesn't exist :: "
132+
f"{self._database_uri.split('/')[-1]}"
122133
)
123134
create_database(self._database_uri)
135+
db_name = self._database_uri.split('/')[-1]
124136
self.cmn_logger.info(
125-
f"Created the database :: {self._database_uri.split('/')[-1]}"
137+
f"Created the database :: {db_name}"
126138
)
127139
else:
140+
db_name = self._database_uri.split('/')[-1]
128141
self.cmn_logger.info(
129-
f"Database already exists :: {self._database_uri.split('/')[-1]}"
142+
f"Database already exists :: {db_name}"
130143
)
131144
return True
132-
except Exception as ex:
133-
self.cmn_logger.error(
134-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
135-
)
145+
except (sqlalchemy.exc.SQLAlchemyError, ValueError) as ex:
136146
self.cmn_logger.error(
137-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
147+
f"Error occurred :: {ex}\tLine No:: "
148+
f"{sys.exc_info()[2].tb_lineno}"
138149
)
139150

140-
def bind_db_app(self, app_instance: flask.Flask) -> Union[SQLAlchemy, None]:
151+
def bind_db_app(self, app_instance: flask.Flask) -> Union[bool, None]:
141152
try:
142153
self.cmn_logger.info(
143-
f"Binding SQLALCHEMY to Application Instance for Service :: [{self.cmn_logger.name}]"
154+
f"Binding SQLALCHEMY to Application Instance for "
155+
f"Service :: [{self.cmn_logger.name}]"
144156
)
145157
app_db = SQLAlchemy(app=app_instance)
146158
self.cmn_logger.info(
147-
f"Bound SQLALCHEMY :: [{app_db}] to Application Instance for Service :: [{self.cmn_logger.name}]"
159+
f"Bound SQLALCHEMY :: [{app_db}] to Application "
160+
f"Instance for Service :: [{self.cmn_logger.name}]"
148161
)
149162
return True
150-
except Exception as ex:
151-
self.cmn_logger.error(
152-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
153-
)
163+
except (ValueError, AttributeError, RuntimeError) as ex:
154164
self.cmn_logger.error(
155-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
165+
f"Error occurred :: {ex}\tLine No:: "
166+
f"{sys.exc_info()[2].tb_lineno}"
156167
)
157168

158169
def migrate_db_bind_app(
159170
self, app_instance: flask.Flask, app_db: SQLAlchemy
160171
) -> Union[Migrate, None]:
161172
try:
162173
self.cmn_logger.info(
163-
f"Binding the db :: [{app_db}] to app instance :: [{app_instance}] for migrations"
174+
f"Binding the db :: [{app_db}] to app instance :: "
175+
f"[{app_instance}] for migrations"
164176
)
165177
migrate_instance = Migrate(app_instance, app_db)
166178
self.cmn_logger.info(
167-
f"Bound the db :: [{app_db}] to app instance :: [{app_instance}] for migrations"
179+
f"Bound the db :: [{app_db}] to app instance :: "
180+
f"[{app_instance}] for migrations"
168181
)
169182
return migrate_instance
170-
except Exception as ex:
171-
self.cmn_logger.error(
172-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
173-
)
183+
except (ValueError, AttributeError, RuntimeError) as ex:
174184
self.cmn_logger.error(
175-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
185+
f"Error occurred :: {ex}\tLine No:: "
186+
f"{sys.exc_info()[2].tb_lineno}"
176187
)
177188

178189
def display_pool_info(self, connection_pool: QueuePool) -> None:
179190
try:
180191
if connection_pool:
181192
self.cmn_logger.info(
182-
"#---------------------------------[ POOL INFO ]----------------------------------------#"
193+
"#---------------------------------[ POOL INFO ]"
194+
"----------------------------------------#"
183195
)
184196
self.cmn_logger.info(
185-
f"Displaying Pool Info for Service ==>[{self.cmn_logger.name}]"
197+
f"Displaying Pool Info for Service "
198+
f"==>[{self.cmn_logger.name}]"
186199
)
200+
pool_id = id(connection_pool)
187201
self.cmn_logger.info(
188-
f"Current Pool Info :: {connection_pool} - ID: {id(connection_pool)}"
202+
f"Current Pool Info :: {connection_pool} - ID: {pool_id}"
189203
)
190204
self.cmn_logger.info(
191205
f"Current Pool Size :: {connection_pool.size()}"
192206
)
207+
checked_in = connection_pool.checkedin()
193208
self.cmn_logger.info(
194-
f"Checked Out Connections from Pool: {connection_pool.checkedin()}"
209+
f"Checked Out Connections from Pool: {checked_in}"
195210
)
211+
checked_out = connection_pool.checkedout()
196212
self.cmn_logger.info(
197-
f"Checked in Connections available in Pool: {connection_pool.checkedout()}"
213+
f"Checked in Connections available in Pool: {checked_out}"
198214
)
199215
self.cmn_logger.info(
200216
f"Current Pool Overflow Info: {connection_pool.overflow()}"
201217
)
202218
self.cmn_logger.info(
203-
"#---------------------------------[ POOL INFO ]----------------------------------------#"
219+
"#---------------------------------[ POOL INFO ]"
220+
"----------------------------------------#"
204221
)
205-
except Exception as ex:
206-
self.cmn_logger.error(
207-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
208-
)
222+
except (AttributeError, RuntimeError) as ex:
209223
self.cmn_logger.error(
210-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
224+
f"Error occurred :: {ex}\tLine No:: "
225+
f"{sys.exc_info()[2].tb_lineno}"
211226
)
212227

213228
def check_db_connectivity_and_retry(
214229
self, db_engine: SQLAlchemy.engine
215230
) -> Union[bool, None]:
216231
try:
217-
# Establishing the connection to the database and create a database/table if not exists
232+
# Establishing the connection to the database and create a
233+
# database/table if not exists
218234
while True:
219-
db_connection_status = self._check_database_connectivity(db_engine)
235+
db_connection_status = (
236+
self._check_database_connectivity(db_engine)
237+
)
220238
if db_connection_status:
221239
break
222240
else:
223241
self.cmn_logger.info(
224-
f"Going for retry .. RETRY_INTERVAL :: {self._retry_interval} sec"
242+
f"Going for retry .. RETRY_INTERVAL :: "
243+
f"{self._retry_interval} sec"
225244
)
226245
time.sleep(self._retry_interval)
227246
return db_connection_status
228-
except Exception as ex:
229-
self.cmn_logger.error(
230-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
231-
)
247+
except (sqlalchemy.exc.SQLAlchemyError, ValueError) as ex:
232248
self.cmn_logger.error(
233-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
249+
f"Error occurred :: {ex}\tLine No:: "
250+
f"{sys.exc_info()[2].tb_lineno}"
234251
)
235252

236253
def _check_database_connectivity(
237254
self, db_engine: SQLAlchemy.engine
238255
) -> Union[bool, None]:
239256
db_connection_status = False
240257
self.cmn_logger.info(
241-
f"Current Connection status set to :: {db_connection_status} for the service :: {self.cmn_logger.name}"
258+
f"Current Connection status set to :: {db_connection_status} "
259+
f"for the service :: {self.cmn_logger.name}"
242260
)
243261
try:
244262
self.cmn_logger.info(
245-
"Trying to establish the connection to the database :: [IN-PROGRESS]"
263+
"Trying to establish the connection to the database "
264+
":: [IN-PROGRESS]"
246265
)
247266
db_connection = db_engine.connect()
248267
self.cmn_logger.info(
249268
"Established the connection to the database :: [SUCCESS]"
250269
)
251270
db_connection_status = True
252271
self.cmn_logger.info(
253-
f"Current Connection status set to :: {db_connection_status} for the service :: {self.cmn_logger.name}"
272+
f"Current Connection status set to :: {db_connection_status} "
273+
f"for the service :: {self.cmn_logger.name}"
254274
)
255275
db_connection.close()
256276
self.cmn_logger.info(
257-
f"Closing the Current Connection as the connection was established for the service :: {self.cmn_logger.name}"
277+
f"Closing the Current Connection as the connection was "
278+
f"established for the service :: {self.cmn_logger.name}"
258279
)
259280
except sqlalchemy.exc.OperationalError as ex:
260281
self.cmn_logger.error(
261282
f"Current Connection status set to :: {db_connection_status}"
262283
)
263284
self.cmn_logger.error(
264-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
285+
f"Error occurred :: {ex}\tLine No:: "
286+
f"{sys.exc_info()[2].tb_lineno}"
265287
)
266288
return db_connection_status
267289

@@ -271,7 +293,8 @@ def create_tables_associated_to_db_model(
271293
connection_status = False
272294
try:
273295
self.cmn_logger.info(
274-
"Trying to create the tables if not present in the database..."
296+
"Trying to create the tables if not present in the "
297+
"database..."
275298
)
276299
# Create all the tables associated with the Base class
277300
self.cmn_logger.info("Going to create the tables ...")
@@ -280,14 +303,17 @@ def create_tables_associated_to_db_model(
280303
self.cmn_logger.info("Created the tables ...")
281304
except sqlalchemy.exc.OperationalError as ex:
282305
self.cmn_logger.error(
283-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
306+
f"Error occurred :: {ex}\tLine No:: "
307+
f"{sys.exc_info()[2].tb_lineno}"
284308
)
285309
except sqlalchemy.exc.TimeoutError as ex:
286310
self.cmn_logger.error(
287-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
311+
f"Error occurred :: {ex}\tLine No:: "
312+
f"{sys.exc_info()[2].tb_lineno}"
288313
)
289-
except Exception as ex:
314+
except (sqlalchemy.exc.SQLAlchemyError, ValueError) as ex:
290315
self.cmn_logger.error(
291-
f"Error occurred :: {ex}\tLine No:: {sys.exc_info()[2].tb_lineno}"
316+
f"Error occurred :: {ex}\tLine No:: "
317+
f"{sys.exc_info()[2].tb_lineno}"
292318
)
293319
return connection_status

0 commit comments

Comments
 (0)