From 8e9abe8eccd1a95d34ab9a6bc7b92d1e660dcae7 Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Thu, 14 Dec 2023 19:21:14 +0300 Subject: Pass connection to `species_by_id` function. To make `species_by_id` function reusable even outside of the application context, pass in the database connection instead of creating the connection inside the function. --- qc_app/dbinsert.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) (limited to 'qc_app/dbinsert.py') diff --git a/qc_app/dbinsert.py b/qc_app/dbinsert.py index ab1c350..2282c8d 100644 --- a/qc_app/dbinsert.py +++ b/qc_app/dbinsert.py @@ -5,6 +5,7 @@ from typing import Union from functools import reduce from datetime import datetime +import MySQLdb as mdb from redis import Redis from MySQLdb.cursors import DictCursor from flask import ( @@ -12,7 +13,7 @@ from flask import ( current_app as app) from . import jobs -from .db_utils import database_connection +from .db_utils import with_db_connection, database_connection dbinsertbp = Blueprint("dbinsert", __name__) @@ -41,17 +42,16 @@ def species() -> tuple: return tuple() -def species_by_id(speciesid) -> Union[dict, None]: +def species_by_id(conn: mdb.Connection, speciesid) -> Union[dict, None]: "Retrieve the species from the database by id." - with database_connection() as conn: - with conn.cursor(cursorclass=DictCursor) as cursor: - cursor.execute( - ( - "SELECT " - "SpeciesId, SpeciesName, LOWER(Name) AS Name, MenuName " - "FROM Species WHERE SpeciesId=%s"), - (speciesid,)) - return cursor.fetchone() + with conn.cursor(cursorclass=DictCursor) as cursor: + cursor.execute( + ( + "SELECT " + "SpeciesId, SpeciesName, LOWER(Name) AS Name, MenuName " + "FROM Species WHERE SpeciesId=%s"), + (speciesid,)) + return cursor.fetchone() def genechips(): "Retrieve the genechip information from the database" @@ -362,7 +362,8 @@ def final_confirmation(): filetype=form["filetype"], totallines=form["totallines"], species=speciesid, genechipid=genechipid, studyid=studyid, datasetid=datasetid, the_species=selected_keys( - species_by_id(speciesid), ("SpeciesName", "Name", "MenuName")), + with_db_connection(lambda conn: species_by_id(conn, speciesid)), + ("SpeciesName", "Name", "MenuName")), platform=selected_keys( platform_by_id(genechipid), ("GeneChipName", "Name", "GeoPlatform", "Title", "GO_tree_value")), -- cgit v1.2.3