aboutsummaryrefslogtreecommitdiff
path: root/qc_app
diff options
context:
space:
mode:
authorFrederick Muriuki Muriithi2023-11-15 09:25:40 +0300
committerFrederick Muriuki Muriithi2023-11-15 09:25:40 +0300
commitfcd4b6fac4296d2b6975e1504dd57d7fc59d3dd5 (patch)
tree867978d988e768c92e8dd75815969223dd883fc3 /qc_app
parentebf61247a66a2ad9d8df5bfbd768855beddce9da (diff)
downloadgn-uploader-fcd4b6fac4296d2b6975e1504dd57d7fc59d3dd5.tar.gz
Commit changes on query success.
Diffstat (limited to 'qc_app')
-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()