From 6cd6446b182ce89398a23de9f857fd7574a2f41c Mon Sep 17 00:00:00 2001 From: Cdvx Date: Wed, 29 Aug 2018 01:33:38 +0300 Subject: [PATCH 1/5] Use db for GET and POST endpoints --- app/routes/routes.py | 92 +++++++++++++++++++++++++++++--------------- connect.py | 25 ++++++------ 2 files changed, 72 insertions(+), 45 deletions(-) diff --git a/app/routes/routes.py b/app/routes/routes.py index 89b9f1a..f083da0 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -104,7 +104,7 @@ def get_question(questionId): questionsList = conn.query_all('questions') if questionsList: for question in questionsList: - if question[3] == questionId: + if int(question[3]) == questionId: temp = { 'questionId': question[3], 'topic': question[1], @@ -132,7 +132,7 @@ def get_answer(questionId, answerId): if questionsList: if answersList: for answer in answersList: - if answer[3] == answerId: + if int(answer[3]) == answerId: temp = { 'answerId': answer[3], 'Qn_Id': answer[1], @@ -153,32 +153,40 @@ def add_question(): current_user = get_jwt_identity() if current_user: request_data = request.get_json() - if (valid_question(request_data)): + print(request_data) + + duplicate_check = valid_question(request_data) + print(duplicate_check) + + if duplicate_check[0]: temp = { 'topic': request_data['topic'], 'body': request_data['body'] } - if len(temp['topic']) != 0 and len(temp['body'])!=0: - question = Question(temp['topic'], temp['body']) - id = question.id - temp['questionId'] = id - conn.insert_new_record('questions', temp) - return jsonify({ - 'msg': f'Question {id} posted successfully', - 'Posted by': f'{current_user}' - }), 201 - return jsonify({'msg': 'topic and body fields should not be empty'}) + question = Question(temp['topic'], temp['body']) + id = question.id + temp['questionId'] = id + conn.insert_new_record('questions', question.__repr__()) + + return jsonify({ + 'msg': f'Question {id} posted successfully', + 'Posted by': f'{current_user}' + }), 201 else: - bad_object = { - "error": "Invalid question object", - "hint": '''Request format should be,{'topic': 'python', - 'body': 'what is python in programming' }''' - } - response = Response(json.dumps([bad_object]), - status=400, mimetype='application/json') - return response + if not duplicate_check[0] and len(duplicate_check) > 1: + reason = duplicate_check[1] + return jsonify({"error": f"{reason}"}) + else: + bad_object = { + "error": "Invalid question object", + "hint": '''Request format should be,{'topic': 'python', + 'body': 'what is python in programming' }''' + } + response = Response(json.dumps([bad_object]), + status=400, mimetype='application/json') + return response return jsonify({ 'message': 'To post a question, you need to be logged in', 'info': 'Signup or login, to get acces_token' @@ -204,7 +212,7 @@ def add_answer(questionId): answer = Answer(temp['body'], temp['Qn_Id']) id = answer.answerId temp['answerId'] = id - conn.insert_new_record('answers', temp) + conn.insert_new_record('answers', answer.__repr__()) return jsonify({ 'msg': f'Answer {id} posted successfully' @@ -262,8 +270,10 @@ def update_question(questionId, topic, body, question_id): question_id, questionId ) - return jsonify({'msg': f'Question {questionId} updated successfully.'}), 204 - return jsonify({'msg': 'body and topic fields should not be empty'}) + return jsonify({ + 'msg': f'Question {questionId} updated successfully.'}), 204 + return jsonify({ + 'msg': 'body and topic fields should not be empty'}) response = Response(json.dumps(['Question not found']), status=404) return response @@ -313,17 +323,35 @@ def valid_username(username): def valid_question(questionObject): - if 'topic' in questionObject and 'body' in questionObject: + if 'topic' and 'body' in questionObject.keys(): questionsList = conn.query_all('questions') - for question in questionsList: - if question['topic'] != questionObject['topic']: - return True - else: - return False + input_topic = questionObject['topic'] + input_body = questionObject['body'] + empty_field = len(input_topic.strip()) and len(input_body.strip()) == 0 + if empty_field: + value = (False, "Question topic or body should not be empty!") + return value + if questionsList: + topics = [question[1] for question in questionsList if question[1] == input_topic] + if len(topics) != 0: + value = (False, "Question topic already exists!") + return value + else: + if len(topics) == 0: + return (True, ) + else: + if 'topic' or 'body' not in questionObject.keys(): + return (False, ) + def valid_answer(answerObject): if 'Qn_Id' in answerObject and 'body' in answerObject: - return True + input_QnId = answerObject['Qn_Id'] + input_body = answerObject['body'] + empty_field = len(input_QnId) and len(input_body.strip()) == 0 + if empty_field: + return (False, "Answer body should not be empty!") + return (True, ) else: - return False + return (False, ) diff --git a/connect.py b/connect.py index 01b7db8..fe05761 100644 --- a/connect.py +++ b/connect.py @@ -5,8 +5,7 @@ class DatabaseConnection(object): def __init__(self): try: self.connection = psycopg2.connect( - "dbname='clvx' user='postgres' host='localhost' password='Tesxting' port='5432'" - ) + "dbname='clvx' user='postgres' host='localhost' password='Tesxting' port='5432'") self.connection.autocommit = True self.cursor = self.connection.cursor() self.queries = [] @@ -22,7 +21,7 @@ def create_Users_table(self): email varchar(100) NOT NULL, password_hash varchar(200) NOT NULL, user_id varchar(150) NOT NULL - )""" + );""" self.cursor.execute(create_table_command) except (Exception, psycopg2.DatabaseError) as error: print(error) @@ -34,8 +33,8 @@ def create_Questions_table(self): id serial PRIMARY KEY, topic varchar(100) NOT NULL, body varchar(600) NOT NULL, - question_id uuid UNIQUE - )""" + question_id varchar(150) NOT NULL + );""" self.cursor.execute(create_table_command) except (Exception, psycopg2.DatabaseError) as error: print(error) @@ -45,12 +44,11 @@ def create_Answers_table(self): self.tablename = 'answers' create_table_command = """CREATE TABLE IF NOT EXISTS answers( id serial PRIMARY KEY, - Qn_Id uuid UNIQUE, + Qn_Id varchar(150) NOT NULL, body varchar(600) NOT NULL, answer_id varchar(150) NOT NULL, - prefered boolean, - FOREIGN KEY (Qn_Id) REFERENCES questions(question_id) - )""" + prefered boolean + );""" self.cursor.execute(create_table_command) except (Exception, psycopg2.DatabaseError) as error: print(error) @@ -69,7 +67,7 @@ def insert_new_record(self, tablename, data): %s, %s, %s - )""" + );""" self.cursor.execute(insert_command, ( data['username'], data['email'], @@ -85,7 +83,7 @@ def insert_new_record(self, tablename, data): %s, %s, %s - )""" + );""" self.cursor.execute(insert_command, ( data['topic'], data['body'], @@ -102,7 +100,7 @@ def insert_new_record(self, tablename, data): %s, %s, %s - )""" + );""" self.cursor.execute(insert_command, ( data['Qn_Id'], data['body'], @@ -154,12 +152,13 @@ def delete_entry(self, tablename, def drop_table(self, tablename): try: - drop_table_command = f"DROP TABLE {tablename}" + drop_table_command = f"DROP TABLE {tablename} CASCADE" self.cursor.execute(drop_table_command) except (Exception, psycopg2.DatabaseError) as error: print(error) conn = DatabaseConnection() +#conn.drop_table('answers') conn.create_Answers_table() conn.create_Users_table() conn.create_Questions_table() From cf8ce0b07ed0b6d1e0a7365bd0682b331d7ed8dc Mon Sep 17 00:00:00 2001 From: Cdvx Date: Wed, 29 Aug 2018 01:36:10 +0300 Subject: [PATCH 2/5] Modify tests --- tests/test_route.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_route.py b/tests/test_route.py index 7878245..003c6ef 100644 --- a/tests/test_route.py +++ b/tests/test_route.py @@ -17,7 +17,7 @@ def test_user_can_login(self): def test_user_can_get_questions(self): with self.client: res = self.client.get('/api/v1/questions') - self.assertEqual(res.status_code, 404) + self.assertEqual(res.status_code, 200) def test_user_can_get_question(self): res = self.client.get('/api/v1/questions/2') @@ -25,7 +25,7 @@ def test_user_can_get_question(self): def test_user_can_get_answers(self): res = self.client.get('/api/v1/questions/2/answers') - self.assertEqual(res.status_code, 404) + self.assertEqual(res.status_code, 200) def test_user_can_get_answer(self): res = self.client.get('/api/v1/questions/2/answers/3') From 50f9f097086b872fa44360c924d969325114ef7f Mon Sep 17 00:00:00 2001 From: Cdvx Date: Wed, 29 Aug 2018 11:40:28 +0300 Subject: [PATCH 3/5] Update question with db [finishes #160126867] --- app/routes/routes.py | 29 ++++++++--------------------- connect.py | 17 ++++++++++++----- tests/test_route.py | 1 + 3 files changed, 21 insertions(+), 26 deletions(-) diff --git a/app/routes/routes.py b/app/routes/routes.py index f083da0..08429b2 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -239,39 +239,26 @@ def add_answer(questionId): @app.route('/api/v1/questions/', methods=['PATCH']) @jwt_required -def update_question(questionId, topic, body, question_id): +def update_question(questionId): current_user = get_jwt_identity() if current_user: request_data = request.get_json() questionsList = conn.query_all('questions') if questionsList: updated_question = dict() - ids = [question[3] for question in questionsList] - + ids = [int(question[3]) for question in questionsList] + print(ids) if questionId in ids: if "topic" in request_data: updated_question["topic"] = request_data["topic"] if "body" in request_data: - updated_question["body"] = request_data["topic"] + updated_question["body"] = request_data["body"] if len(updated_question['topic'])!=0 and len(updated_question['body'])!=0: for question in questionsList: - if question["questionId"] == questionId: - conn.update_entry( - 'questions', - topic, - updated_question['topic'], - question_id, - questionId - ) - conn.update_entry( - 'questions', - body, - updated_question['body'], - question_id, - questionId - ) - return jsonify({ - 'msg': f'Question {questionId} updated successfully.'}), 204 + if int(question[3]) == questionId: + print(type(question[1])) + conn.update_question(updated_question['topic'], updated_question['body'], str(questionId)) + return jsonify({'msg': f'Question {questionId} updated successfully.'}), 200 return jsonify({ 'msg': 'body and topic fields should not be empty'}) diff --git a/connect.py b/connect.py index fe05761..85ecfec 100644 --- a/connect.py +++ b/connect.py @@ -131,12 +131,19 @@ def query_all(self, tablename): else: return queries - def update_entry(self, tablename, variable, - new_value, identifier, id_value): + def update_question(self, new_topic, new_body, questionId): try: - update_command = f"""UPDATE {tablename} - SET {variable}={new_value} - WHERE {identifier}={id_value}""" + update_command = """UPDATE questions SET topic = %s, body = %s + WHERE question_id = %s""" + self.cursor.execute(update_command, (new_topic, new_body, questionId)) + except (Exception, psycopg2.DatabaseError) as error: + print(error) + + def update_answer(self, new_body, id_value): + try: + update_command = f"""UPDATE answers + SET body ={new_body} + WHERE Qn_Id ={id_value}""" self.cursor.execute(update_command) except (Exception, psycopg2.DatabaseError) as error: print(error) diff --git a/tests/test_route.py b/tests/test_route.py index 003c6ef..bd10af8 100644 --- a/tests/test_route.py +++ b/tests/test_route.py @@ -46,6 +46,7 @@ def test_user_post_answer(self): "body": "what is software?", "Qn_Id": 2 } + res = self.client.post('/api/v1/questions/4/answers', json=answer) self.assertEqual(res.status_code, 401) From 1951c4459b18e1cc6f5a0122f9f58b785939c01b Mon Sep 17 00:00:00 2001 From: Cdvx Date: Wed, 29 Aug 2018 15:23:39 +0300 Subject: [PATCH 4/5] Implement LFA feedback --- app/models.py | 10 ++-- app/routes/routes.py | 134 ++++++++++++++++++++++++------------------- connect.py | 26 ++++----- 3 files changed, 94 insertions(+), 76 deletions(-) diff --git a/app/models.py b/app/models.py index 2bfbb68..109bad1 100644 --- a/app/models.py +++ b/app/models.py @@ -7,8 +7,8 @@ class Question: def __init__(self, topic, body): self.id = uuid.uuid4().int - self.topic = topic.strip() - self.body = body.strip() + self.topic = str(topic).strip() + self.body = str(body).strip() def __repr__(self): return { @@ -21,7 +21,7 @@ def __repr__(self): class Answer: def __init__(self, body, Qn_Id, pref=False): self.answerId = uuid.uuid4().int - self.body = body.strip() + self.body = str(body).strip() self.Qn_Id = Qn_Id self.prefered = pref @@ -41,8 +41,8 @@ class User: def __init__(self, username, email, password): self.salt = bcrypt.gensalt() self.id = uuid.uuid4().int - self.username = username.strip() - self.email = email.strip() + self.username = str(username).strip() + self.email = str(email).strip() self.password_hash = generate_password_hash(password) def __repr__(self): diff --git a/app/routes/routes.py b/app/routes/routes.py index 08429b2..85fc163 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -53,7 +53,7 @@ def signup(): if not request.is_json: return jsonify({'message': 'JSON missing in request!'}), 400 - username = request.args.get('username', None).split() + username = str(request.args.get('username', None)).split() email = request.args.get('email', None) password = request.args.get('password', None) repeat_password = request.args.get('repeat_password', None) @@ -62,33 +62,37 @@ def signup(): return jsonify({ 'message': 'Required parameter: username missing!' }), 400 - elif not email: - return jsonify({'message': 'Required parameter: email missing!'}), 400 - elif not password: - return jsonify({'message': 'Required parameter: email missing!'}), 400 else: - if not repeat_password: - msg = 'Required parameter: repeat_password missing!' - return jsonify({'message': f'{msg}'}), 400 - users = conn.query_all('users') - print(users) - if len(username) > 1: - username_ = username[0] + " " + username[1] - print(username_) - username = username[0] - if valid_username(username): - - if repeat_password == password: - user = User(username, email, password) - conn.insert_new_record('users', user.__repr__()) - return jsonify({ - 'success': f"{username}'s account created succesfully" - }), 200 + if username: + if len(username) > 1: + username_ = username[0] + " " + username[1] + username = username_ + if not valid_username(username): + return jsonify({'message': f'username {username} already taken!'}), 401 + elif len(username) == 1: + username = username[0] + if not valid_username(username): + return jsonify({'message': f'username {username} already taken!'}), 401 + if not email: + return jsonify({'message': 'Required parameter: email missing!'}), 400 + elif not password: + return jsonify({'message': 'Required parameter: password missing!'}), 400 + else: + if not repeat_password: + msg = 'Required parameter: repeat_password missing!' + return jsonify({'message': f'{msg}'}), 400 - return jsonify({ - 'message': 'Password does not match repeat_password' - }), 401 - return jsonify({'message': f'username {username} already taken!'}), 401 + if repeat_password == password: + user = User(username, email, password) + conn.insert_new_record('users', user.__repr__()) + return jsonify({ + 'success': f"{username}'s account created succesfully" + }), 200 + else: + if repeat_password != password: + return jsonify({ + 'message': 'Password does not match repeat_password' + }), 401 @app.route('/api/v1/questions', methods=['GET']) @@ -120,8 +124,10 @@ def get_question(questionId): def get_answers(questionId): answersList = conn.query_all('answers') if answersList: - return jsonify({'answers': answersList}), 200 - return jsonify({'message': 'No Answers added yet'}), 404 + for answer in answersList: + if int(answer[1]) == questionId: + return jsonify({'answers': answersList}), 200 + return jsonify({'message': f'No Answers added yet for question {questionId}'}), 404 @app.route('/api/v1/questions//answers/', @@ -201,33 +207,38 @@ def add_answer(questionId): request_data = request.get_json() questionsList = conn.query_all('questions') if questionsList: - - if (valid_answer(request_data)): - + answer_check = valid_answer(request_data) + ids = [int(qn[3]) for qn in questionsList] + if answer_check[0] and request_data['Qn_Id'] in ids: temp = { 'Qn_Id': request_data['Qn_Id'], 'body': request_data['body'] } - if len(temp['Qn_Id'])!=0 and len(temp['body'])!=0: - answer = Answer(temp['body'], temp['Qn_Id']) - id = answer.answerId - temp['answerId'] = id - conn.insert_new_record('answers', answer.__repr__()) + answer = Answer(temp['body'], temp['Qn_Id']) + id = answer.answerId + temp['answerId'] = id + conn.insert_new_record('answers', answer.__repr__()) - return jsonify({ - 'msg': f'Answer {id} posted successfully' - }), 201 - return jsonify({'msg': 'body and Qn_Id fields should not be empty'}) + return jsonify({ + 'msg': f'Answer {id} posted successfully' + }), 201 + # return jsonify({'msg': 'body and Qn_Id fields should not be empty'}) else: - bad_object = { - "error": "Invalid answer object", - "hint": '''Request format should be { - 'body': 'this is the body', - 'Qn_Id': 2}''' - } - response = Response(json.dumps([bad_object]), - status=400, mimetype='application/json') - return response + + if not answer_check[0] and len(answer_check) > 1: + reason = answer_check[1] + return jsonify({"error": f"{reason}"}) + else: + bad_object = { + "error": "Invalid answer object", + "hint": '''Request format should be { + 'body': 'this is the body', + 'Qn_Id': 2}''', + "hint2": f"Qn_Id should correspond with {questionId}" + } + response = Response(json.dumps([bad_object]), + status=400, mimetype='application/json') + return response return jsonify({f'Attempt to answer Question {questionId}': f'Question {questionId} does not exist.'}), 404 @@ -310,20 +321,24 @@ def valid_username(username): def valid_question(questionObject): - if 'topic' and 'body' in questionObject.keys(): + if 'topic' in questionObject.keys() and 'body' in questionObject.keys(): questionsList = conn.query_all('questions') input_topic = questionObject['topic'] input_body = questionObject['body'] - empty_field = len(input_topic.strip()) and len(input_body.strip()) == 0 - if empty_field: - value = (False, "Question topic or body should not be empty!") + empty_field = len(str(input_topic).strip()) and len(str(input_body).strip()) == 0 + check_type = type(input_topic) == int or type(input_body) == int + print(check_type) + if empty_field or check_type: + value = (False, {"hint_1":"Question topic or body should not be empty!", + "hint_2":"body and topic fileds should not consist entirely of integer-type data"} + ) return value if questionsList: topics = [question[1] for question in questionsList if question[1] == input_topic] if len(topics) != 0: value = (False, "Question topic already exists!") - return value + return value else: if len(topics) == 0: return (True, ) @@ -333,12 +348,15 @@ def valid_question(questionObject): def valid_answer(answerObject): - if 'Qn_Id' in answerObject and 'body' in answerObject: + if 'Qn_Id' in answerObject.keys() and 'body' in answerObject.keys(): input_QnId = answerObject['Qn_Id'] input_body = answerObject['body'] - empty_field = len(input_QnId) and len(input_body.strip()) == 0 - if empty_field: - return (False, "Answer body should not be empty!") + empty_field = len(str(input_QnId)) and len(input_body.strip()) == 0 + check_type = type(input_QnId) == str or type(input_body) == int + if empty_field or check_type: + return (False, {'hint': "Answer body should not be empty!", + 'hint2': "body and topic fileds should not contain numbers only and string-type data respectively"} + ) return (True, ) else: return (False, ) diff --git a/connect.py b/connect.py index 85ecfec..5c4307e 100644 --- a/connect.py +++ b/connect.py @@ -8,7 +8,7 @@ def __init__(self): "dbname='clvx' user='postgres' host='localhost' password='Tesxting' port='5432'") self.connection.autocommit = True self.cursor = self.connection.cursor() - self.queries = [] + self.last_ten_queries = [] except: print("Cannot connect to database.") @@ -122,9 +122,9 @@ def query_all(self, tablename): if items: for item in items: queries.append(item) - if len(self.queries) == 11: - self.queries.pop() - self.queries.append(item) + if len(self.last_ten_queries) == 11: + self.last_ten_queries.pop() + self.last_ten_queries.append(item) return queries except (Exception, psycopg2.DatabaseError) as error: print(error) @@ -139,19 +139,19 @@ def update_question(self, new_topic, new_body, questionId): except (Exception, psycopg2.DatabaseError) as error: print(error) - def update_answer(self, new_body, id_value): - try: - update_command = f"""UPDATE answers - SET body ={new_body} - WHERE Qn_Id ={id_value}""" - self.cursor.execute(update_command) - except (Exception, psycopg2.DatabaseError) as error: - print(error) + # def update_answer(self, new_body, id_value): + # try: + # update_command = f"""UPDATE answers + # SET body ={new_body} + # WHERE Qn_Id ={id_value}""" + # self.cursor.execute(update_command) + # except (Exception, psycopg2.DatabaseError) as error: + # print(error) def delete_entry(self, tablename, identifier, id_value): try: - delete_command = f"""DELETE {tablename} + delete_command = """DELETE {tablename} WHERE {identifier} = {id_value}""" self.cursor.execute(delete_command) except (Exception, psycopg2.DatabaseError) as error: From 54b64f502f85cbb5e44e1158b843253cc8d0594a Mon Sep 17 00:00:00 2001 From: Cdvx Date: Wed, 29 Aug 2018 17:07:09 +0300 Subject: [PATCH 5/5] Get all required endpoints [finishes #160136546] to work with database and test with postman --- app/models.py | 4 +-- app/routes/routes.py | 84 +++++++++++++++++++++++++++++++++++++++----- connect.py | 35 +++++++++++------- 3 files changed, 100 insertions(+), 23 deletions(-) diff --git a/app/models.py b/app/models.py index 109bad1..f22104c 100644 --- a/app/models.py +++ b/app/models.py @@ -33,8 +33,8 @@ def __repr__(self): 'prefered': self.prefered } - def prefer_answer(self, answer): - answer.prefered = True + def prefer_answer(self): + self.prefered = True class User: diff --git a/app/routes/routes.py b/app/routes/routes.py index 85fc163..848038a 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -117,7 +117,7 @@ def get_question(questionId): return jsonify(temp), 200 return Response(json.dumps(['Question not Found']), status=404, mimetype='application/json') - return jsonify({f'Question {questionId}': 'Has not been added yet'}), 404 + return jsonify({f'Question {questionId}': 'Has not been added yet'}), 200 @app.route('/api/v1/questions//answers', methods=['GET']) @@ -248,6 +248,50 @@ def add_answer(questionId): }), 401 +@app.route('/api/v1/questions//answers/', methods=['PUT']) +@jwt_required +def select_answer_as_preferred(questionId, answerId): + current_user = get_jwt_identity() + if current_user: + request_data = request.get_json() + questionsList = conn.query_all('questions') + + if questionsList: + answer_check = valid_answer(request_data) + ids = [int(qn[3]) for qn in questionsList] + if answer_check[0] and request_data['Qn_Id'] in ids: + + conn.update_answer(str(answerId)) + + return jsonify({ + 'msg': f"Answer {answerId} marked as preferred" + }), 201 + # return jsonify({'msg': 'body and Qn_Id fields should not be empty'}) + else: + + if not answer_check[0] and len(answer_check) > 1: + reason = answer_check[1] + return jsonify({"error": f"{reason}"}) + else: + bad_object = { + "error": "Invalid answer object", + "hint": '''Request format should be { + 'body': 'this is the body', + 'Qn_Id': 2}''', + "hint2": f"Qn_Id should correspond with {questionId}" + } + response = Response(json.dumps([bad_object]), + status=400, mimetype='application/json') + return response + return jsonify({f'Attempt to select answer to Question {questionId} as prefered': + f'Question {questionId} does not exist.'}), 404 + + return jsonify({ + 'message': 'To post an answer, you need to be logged in', + 'info': 'Signup or login, to get access_token' + }), 401 + + @app.route('/api/v1/questions/', methods=['PATCH']) @jwt_required def update_question(questionId): @@ -284,20 +328,22 @@ def update_question(questionId): @app.route('/api/v1/questions/', methods=['DELETE']) @jwt_required -def delete_question(questionId, question_id): +def delete_question(questionId): current_user = get_jwt_identity() if current_user: questionsList = conn.query_all('questions') if questionsList: - ids = [question[3] for question in questionsList] + ids = [int(question[3]) for question in questionsList] if questionId in ids: + print('yeah') for question in questionsList: - if questionId == question[3]: + if questionId == int(question[3]): questionsList.remove(question) - conn.delete_entry('questions', question_id, questionId) - response = Response( - '', status=200, mimetype='application/json') - return response + conn.delete_entry('questions', str(questionId)) + message = {'success': f"Question {questionId} deleted successfully!"} + response = Response( + json.dumps(message), status=202, mimetype='application/json') + return response response = Response(json.dumps(['Question not found']), status=404, mimetype='application/json') return response @@ -360,3 +406,25 @@ def valid_answer(answerObject): return (True, ) else: return (False, ) + +@app.errorhandler(500) +def internal_sserver_error(e): + msg = "Sorry,we are experiencing some technical difficulties" + msg2 = "Please report this to cedriclusiba@gmail.com and check back with us soon" + return jsonify({'error': msg, "hint": msg2}), 500 + +@app.errorhandler(404) +def url_unknown(e): + return jsonify({"error": "Sorry, resource you are looking for does not exist"}), 404 + +@app.errorhandler(405) +def method_not_allowed(e): + return jsonify({'error': "Sorry, this action is not supported for this url"}), 405 + +@app.errorhandler(403) +def forbidden_resource(e): + return jsonify({'error': "Sorry, resource you are trying to access is forbidden"}), 403 + +@app.errorhandler(410) +def deleted_resource(e): + return jsonify({'error': "Sorry, this resource was deleted"}), 410 \ No newline at end of file diff --git a/connect.py b/connect.py index 5c4307e..6316dc5 100644 --- a/connect.py +++ b/connect.py @@ -139,21 +139,30 @@ def update_question(self, new_topic, new_body, questionId): except (Exception, psycopg2.DatabaseError) as error: print(error) - # def update_answer(self, new_body, id_value): - # try: - # update_command = f"""UPDATE answers - # SET body ={new_body} - # WHERE Qn_Id ={id_value}""" - # self.cursor.execute(update_command) - # except (Exception, psycopg2.DatabaseError) as error: - # print(error) + def update_answer(self, answerId): + try: + update_command = """UPDATE answers SET prefered = %s WHERE answer_id = %s""" + self.cursor.execute(update_command, (True, str(answerId))) + except (Exception, psycopg2.DatabaseError) as error: + print(error) + - def delete_entry(self, tablename, - identifier, id_value): + def delete_entry(self, tablename, id_value): try: - delete_command = """DELETE {tablename} - WHERE {identifier} = {id_value}""" - self.cursor.execute(delete_command) + if tablename == 'questions': + delete_command = """DELETE FROM questions + WHERE question_id = %s""" + self.cursor.execute(delete_command, (id_value, )) + + if tablename == 'answers': + delete_command = """DELETE FROM answers + WHERE answer_id = %s""" + self.cursor.execute(delete_command, (id_value, )) + + if tablename == 'users': + delete_command = """DELETE FROM users + WHERE user_id = %s""" + self.cursor.execute(delete_command, (id_value, )) except (Exception, psycopg2.DatabaseError) as error: print(error)