From 7f615bbdf1778f9c114ced29ec652875005b533e Mon Sep 17 00:00:00 2001 From: mst Date: Tue, 26 Nov 2024 15:11:59 +0300 Subject: [PATCH] move addAnswer logic into functions --- app.py | 22 +--------------------- functions.py | 29 ++++++++++++++++++++++++++--- 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/app.py b/app.py index e15fadd..9bf5b09 100644 --- a/app.py +++ b/app.py @@ -436,27 +436,7 @@ def addAnswer(): if not answer: abort(400, "Missing 'answer' attribute or 'answer' is empty") - conn = func.connectToDb() - try: - cursor = conn.cursor() - - app.logger.debug("[CatAsk/API/add_answer] INSERT'ing an answer into database") - - cursor.execute("INSERT INTO answers (question_id, content, cw) VALUES (%s, %s, %s)", (question_id, answer, cw)) - answer_id = cursor.lastrowid - - app.logger.debug("[CatAsk/API/add_answer] UPDATE'ing question to set answered and answer_id") - - cursor.execute("UPDATE questions SET answered=%s, answer_id=%s WHERE id=%s", (True, answer_id, question_id)) - conn.commit() - except Exception as e: - conn.rollback() - return jsonify({'error': str(e)}), 500 - finally: - cursor.close() - conn.close() - - return jsonify({'message': 'Answer added successfully!'}), 201 + return func.addAnswer(question_id, answer, cw) # -- uploaders -- diff --git a/functions.py b/functions.py index bd3fb16..aa259e1 100644 --- a/functions.py +++ b/functions.py @@ -206,13 +206,36 @@ def getAnswer(question_id: int): conn.close() return answer +def addAnswer(question_id, answer, cw): + conn = connectToDb() + try: + cursor = conn.cursor() + + app.logger.debug("[CatAsk/API/add_answer] INSERT'ing an answer into database") + + cursor.execute("INSERT INTO answers (question_id, content, cw) VALUES (%s, %s, %s)", (question_id, answer, cw)) + answer_id = cursor.lastrowid + + app.logger.debug("[CatAsk/API/add_answer] UPDATE'ing question to set answered and answer_id") + + cursor.execute("UPDATE questions SET answered=%s, answer_id=%s WHERE id=%s", (True, answer_id, question_id)) + conn.commit() + except Exception as e: + conn.rollback() + return jsonify({'error': str(e)}), 500 + finally: + cursor.close() + conn.close() + + return jsonify({'message': 'Answer added successfully!'}), 201 + def readPlainFile(file, split=False): if os.path.exists(file): with open(file, 'r', encoding="utf-8") as file: - if split == False: - return file.read() - if split == True: + if split: return file.read().splitlines() + else: + return file.read() else: return []