Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ def delete_entry(self, tablename, id_value):
print(error)

def drop_table(self, tablename):

try:
drop_table_command = f"DROP TABLE {tablename} CASCADE"
self.cursor.execute(drop_table_command)
Expand Down
234 changes: 139 additions & 95 deletions app/routes/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
from flask import Flask, Response, json, jsonify, request, url_for
from flask_jwt_extended import (JWTManager, create_access_token,
get_jwt_identity, jwt_required)

from werkzeug.security import check_password_hash

from app import app
from app.models import (Answer, Question, User, valid_answer, valid_login_data,
valid_question, valid_username, valid_signup_data)
from app.connect import conn
from app.models import (Answer, Question, User, valid_answer, valid_login_data,
valid_question, valid_signup_data, valid_username)


@app.route('/')
Expand Down Expand Up @@ -48,7 +48,7 @@ def login():
)
msg = {'access_token': f'{access_token}'}

return jsonify({f'access token created for user {username}': msg}), 200
return jsonify({f'User:{username} logged in.': msg}), 200
msg = {"error": "Invalid login data",
"Hint": """required formart is: {'username':'xyz',
'password': 'xyh12',}"""}
Expand All @@ -62,50 +62,60 @@ def signup():
return jsonify({'message': 'JSON missing in request!'}), 400

if valid_signup_data(request_data):
print('valid data')
username = str(request_data['username']).split()
email = request_data['email']
password = request_data['password']
repeat_password = request_data['repeat_password']

if not username:
print('not username')
return jsonify({
'message': 'Required parameter: username missing!'
}), 400
else:
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:
elif username:
print('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
else:
if 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

if repeat_password == password:

user = User(username, email, password)
conn.insert_new_record('users', user.__repr__())

return jsonify({
'success': f"{username}'s account created successfully"
}), 200
else:
if repeat_password != password:
return jsonify({'message': f'Username: {username} already taken!'}), 401

if not email or len(email.strip()) == 0:
print("not email, valid username")
return jsonify({'message': 'Required parameter: email missing!'}), 400
if username and email:
print('valid username and email')
if not password or len(str(password).strip()) == 0:
print("not password")
return jsonify({'message': 'Required parameter: password missing!'}), 400

if username and email and password:
if not repeat_password or len(str(repeat_password).strip()) == 0:
print("not_repeat pw")
msg = 'Required parameter: repeat_password missing!'
return jsonify({'message': f'{msg}'}), 400
else:
if repeat_password:
if repeat_password == password:
user = User(username, email, password)
conn.insert_new_record('users', user.__repr__())

return jsonify({
'message': 'Password does not match repeat_password'
}), 401
'success': f"{username}'s account created successfully"
}), 200
else:
if repeat_password != password:
return jsonify({
'message': 'Password does not match repeat_password'
}), 401
msg = {"error": "Invalid signup data",
"Hint": """required formart is: {'username':'xyz',
"Hint": """required formart is: {'username':'xyz',
'email':'xyz@gmail.com',
'password': 'xyh12',
'repeat_password':'xyh12'}"""}
Expand All @@ -126,47 +136,78 @@ def get_questions():
}
questions.append(temp)
return jsonify({'questions': questions}), 200
return jsonify({'message': 'No Questions added yet'}), 404
return jsonify({'message': 'No Questions added.'}), 404


@app.route('/api/v1/questions/<int:questionId>', methods=['GET'])
def get_question(questionId):
questionsList = conn.query_all('questions')
answersList = conn.query_all('answers')
answers = [[ans[2]] for ans in answersList if int(ans[1]) == questionId]
ans_list= []

if questionsList:
for question in questionsList:
if int(question[4]) == questionId:
question = [qn for qn in questionsList if int(qn[4])==questionId]
if question and not answersList:
print(question)
temp = {
'questionId': question[0][4],
'topic': question[0][1],
'body': question[0][2],
'author': question[0][3]
}
return jsonify(temp), 200
if question and answersList:
answers = [ans for ans in answersList if int(ans[1]) == questionId]
if answers:
for ans in answers:
temp1 = {
'answerId': ans[3],
'body': ans[2],
'author': ans[4],
'prefered': ans[5],
'questionId': ans[1]
}

ans_list.append(temp1)
temp = {
'questionId': question[4],
'topic': question[1],
'body': question[2],
'author': question[3],
'answers': answers
'questionId': question[0][4],
'topic': question[0][1],
'body': question[0][2],
'author': question[0][3],
'answers': ans_list
}
return jsonify(temp), 200

return Response(json.dumps(['Question not Found']),
status=404, mimetype='application/json')
return jsonify({f'Question {questionId}': 'does not exist.'}), 200

return jsonify({'message': 'No questions added.'}), 200


@app.route('/api/v1/questions/<int:questionId>/answers', methods=['GET'])
def get_answers(questionId):
answersList = conn.query_all('answers')
answers = []
if answersList:
for answer in answersList:
if int(answer[1]) == questionId:
temp = {
'answerId': answer[3],
'author': answer[4],
'body': answer[2],
'prefered': answer[5],
'questionId': answer[1]
}
answers.append(temp)
return jsonify({'answers': answers}), 200
return jsonify({'message': f'No Answers added for question {questionId}.'}), 404
questionsList = conn.query_all('questions')
if questionsList:
questions = [qn for qn in questionsList if int(qn[4]) == questionId]
if questions:
answers = []
if answersList:
for answer in answersList:
if int(answer[1]) == questionId:
temp = {
'answerId': answer[3],
'author': answer[4],
'body': answer[2],
'prefered': answer[5],
'questionId': answer[1]
}
answers.append(temp)
return jsonify({'answers': answers}), 200
return jsonify({'message': 'Answer not found!'}), 404
return jsonify({'message': 'No Answers added.'}), 404
return jsonify({'message': 'Question not found!'}), 404
return jsonify({'message': 'No questions added!'}), 404


@app.route('/api/v1/questions/<int:questionId>/answers/<int:answerId>',
Expand All @@ -188,11 +229,9 @@ def get_answer(questionId, answerId):
'QuestionId': answer[1]
}
return jsonify(temp), 200
return Response(json.dumps(['Answer not Found']),
status=404, mimetype='application/json')
return jsonify({
f'Answer{answerId} for Question{questionId}': 'not found.'
}), 404
return Response(json.dumps(['Answer not found!']),
status=404, mimetype='application/json')
return jsonify({'message': 'Question not found!'}), 404


@app.route('/api/v1/questions', methods=['POST'])
Expand All @@ -216,8 +255,8 @@ def add_question():
conn.insert_new_record('questions', question.__repr__())

return jsonify({
'msg': f'Question {question.id} posted successfully',
'Posted by': f'{current_user}'
'message': 'Question posted successfully',
'question': question.__repr__()
}), 201

else:
Expand Down Expand Up @@ -249,7 +288,7 @@ def add_answer(questionId):
if questionsList:
answer_check = valid_answer(request_data)
ids = [int(qn[4]) for qn in questionsList]
if answer_check[0]:
if answer_check[0] and questionId in ids:
temp = {
'Qn_Id': questionId,
'body': request_data['body']
Expand All @@ -259,7 +298,8 @@ def add_answer(questionId):
conn.insert_new_record('answers', answer.__repr__())

return jsonify({
'msg': f'Answer {answer.answerId} posted successfully'
'message': 'Answer posted successfully',
'answer': answer.__repr__()
}), 201

else:
Expand All @@ -277,8 +317,8 @@ def add_answer(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
return jsonify({f'Attempt to answer Question with Id:{questionId}':
'Question not found!.'}), 404

return jsonify({
'message': 'To post an answer, you need to be logged in',
Expand All @@ -291,40 +331,39 @@ def add_answer(questionId):
def select_answer_as_preferred(questionId, answerId):
current_user = get_jwt_identity()
if current_user:
request_data = request.get_json()
# request_data = request.get_json()
questionsList = conn.query_all('questions')
answersList = conn.query_all('answers')

if questionsList:
if answersList or questionsList:

#answer_check = valid_answer(request_data)
usr = [qn[3] for qn in questionsList if int(qn[4]) == questionId]

answer = [ans for ans in answersList if int(ans[1]) == questionId and int(ans[3]) == answerId]

if usr and usr[0] == current_user:

conn.update_answer(str(answerId))

return jsonify({
'msg': f"Answer {answerId} marked as preferred"
}), 201
else:
if answer[0]:

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}'''
conn.update_answer(str(answerId))
temp = {
'answerId': answer[0][3],
'body': answer[0][2],
'author': answer[0][4],
'prefered': True,
'questionId': answer[0][1]
}
response = Response(json.dumps([bad_object]),
status=400, mimetype='application/json')
return response
return jsonify({
'message': "Answer marked as preferred",
'answer': temp
}), 201

return jsonify({'message': 'Answer not found!'}), 404
return jsonify({'Access denied':
f'Only question auhtor:{current_user} can perform this action!'})
return jsonify({f'Attempt to select answer to Question {questionId} as prefered':
f'Question {questionId} does not exist.'}), 404
return jsonify({'message':
'Question not found'}), 404

return jsonify({
'message': 'To post an answer, you need to be logged in',
Expand Down Expand Up @@ -360,8 +399,13 @@ def update_question(questionId):
updated_question['topic'],
updated_question['body'],
str(questionId))
msg = f'Question {questionId} updated successfully.'
return jsonify({'msg': msg}), 200
temp = {
'new_topic': updated_question['topic'],
'new_body': updated_question['body']
}
msg = 'Question updated successfully.'
return jsonify({'message': msg,
'updated_question': temp}), 200
return jsonify({
'msg': 'body and topic fields should not be empty'})
msg = f'Only question auhtor:{current_user} can perform this action!'
Expand Down Expand Up @@ -394,7 +438,7 @@ def delete_question(questionId):
conn.delete_entry('questions', str(questionId))

message = {
'success': f"Question {questionId} deleted successfully!"}
'success': f"Question deleted!"}
response = Response(
json.dumps(message), status=202, mimetype='application/json')
return response
Expand Down
Loading