2021-01-16 19:47:34 +01:00
|
|
|
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',
|
2021-01-17 18:16:36 +01:00
|
|
|
pool_size = 5,
|
|
|
|
pool_reset_connection = True
|
2021-01-16 19:47:34 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
def getConnection():
|
|
|
|
global pool
|
|
|
|
return pool.get_connection()
|
2021-01-17 00:20:42 +01:00
|
|
|
|
|
|
|
|
2021-01-17 14:45:11 +01:00
|
|
|
def getMany(stmt, params, objName):
|
2021-01-17 00:20:42 +01:00
|
|
|
try:
|
|
|
|
dbh = getConnection()
|
|
|
|
objs = []
|
|
|
|
cur = dbh.cursor(dictionary=True)
|
2021-01-17 14:45:11 +01:00
|
|
|
cur.execute(stmt, params)
|
2021-01-17 00:20:42 +01:00
|
|
|
for obj in cur:
|
|
|
|
objs.append(obj)
|
|
|
|
return objs
|
|
|
|
except Exception as err:
|
|
|
|
return str(err), 500
|
|
|
|
finally:
|
2021-01-17 18:16:36 +01:00
|
|
|
print("return connection in getMany")
|
|
|
|
cur.close()
|
2021-01-17 00:20:42 +01:00
|
|
|
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:
|
2021-01-17 18:16:36 +01:00
|
|
|
print("return connection in getOne")
|
|
|
|
cur.close()
|
2021-01-17 00:20:42 +01:00
|
|
|
dbh.close()
|
|
|
|
|