import mariadb import os pool = None def createConnectionPool(): global pool try: user = os.environ["DB_USER"] password = os.environ["DB_PASS"] host = os.environ["DB_HOST"] database = os.environ["DB_NAME"] except KeyError as err: raise Exception("Database configuration variable {} not available".format(err)) pool = mariadb.ConnectionPool( user = user, password = password, host = host, database = database, pool_name = 'hv-wep-app', pool_size = 5 ) def getConnection(): global pool return pool.get_connection() def getMany(stmt, params, objName): try: dbh = getConnection() objs = [] cur = dbh.cursor(dictionary=True) cur.execute(stmt, params) for obj in cur: objs.append(obj) return objs except Exception as err: return str(err), 500 finally: dbh.close() def getOne(stmt, params, objName): try: dbh = getConnection() cur = dbh.cursor(dictionary=True) cur.execute(stmt, params) obj = cur.next() if not obj: return "{} not found".format(objName), 404 invObj = cur.next() if invObj: return "More than one {} by that id ({}, {})".format(objName, id, invObj), 500 return obj except Exception as err: return str(err), 500 finally: dbh.close()