aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--qc_app/db_utils.py19
1 files changed, 16 insertions, 3 deletions
diff --git a/qc_app/db_utils.py b/qc_app/db_utils.py
index 98f8332..7eca93a 100644
--- a/qc_app/db_utils.py
+++ b/qc_app/db_utils.py
@@ -1,5 +1,8 @@
"""module contains all db related stuff"""
-from typing import Tuple, Optional
+import logging
+import traceback
+import contextlib
+from typing import Tuple, Optional, Iterator
from urllib.parse import urlparse
import MySQLdb as mdb
@@ -14,8 +17,18 @@ def parse_db_url(db_url) -> Tuple:
parsed_db.password, parsed_db.path[1:], parsed_db.port)
-def database_connection(db_url: Optional[str] = None) -> mdb.Connection:
+@contextlib.contextmanager
+def database_connection(db_url: Optional[str] = None) -> Iterator[mdb.Connection]:
"""function to create db connector"""
host, user, passwd, db_name, db_port = parse_db_url(
db_url or app.config["SQL_URI"])
- return mdb.connect(host, user, passwd, db_name, port=(db_port or 3306))
+ connection = mdb.connect(
+ host, user, passwd, db_name, port=(db_port or 3306))
+ try:
+ yield connection
+ connection.commit()
+ except mdb.Error as _mdb_err:
+ logging.debug(traceback.format_exc())
+ connection.rollback()
+ finally:
+ connection.close()