def get(self): """Get all quizzes""" logs.debug_ ("_______________________________________________") logs.debug_ ("QuizzesAPI get fn: %s" %(request)) # Query quizzes for this admin from quiz table # Should that be the case or should admin be able to see # other quizzes as well userid, username = utls.get_user_from_hdr() query_obj = models.Quiz.query.filter_by(userid=userid).all() if not query_obj: response = handle_invalid_usage(InvalidUsageException ('Error: No quizzes found', status_code=404)) return response if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Return response resource_fields = {} resource_fields['qzid'] =fields.Integer resource_fields['title']=fields.String resource_fields['difficulty_level'] =fields.String resource_fields['text'] =fields.String resource_fields['no_ques']=fields.Integer quizzes = marshal(query_obj, resource_fields) response = jsonify(quizzes=quizzes) response.status_code = 200 logs.info_(response) utls.display_tables() return response
def get(self): """Get all quizzes""" logs.debug_ ("_______________________________________________") logs.debug_ ("QuizzesAPI get fn: %s" %(request)) userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Query from quiz table query_obj = models.Quiz.query.order_by(models.Quiz.qzid).all() if not query_obj: response = handle_invalid_usage(InvalidUsageException ('Error: No quizzes found', status_code=404)) return response # Return response resource_fields = {'qzid':fields.Integer, 'title':fields.String } user = marshal(query_obj, resource_fields) response = jsonify(user=user) response.status_code = 200 logs.info_(response) utls.display_tables() return response
def get(self, qzid): """Get quiz details""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuizAPI get fn: %s" %(request)) userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Query from quiz table query_obj = models.Quiz.query.filter_by(qzid=qzid).all() if not query_obj: response = handle_invalid_usage(InvalidUsageException ('Error: Quiz not found', status_code=404)) return response # Return response resource_fields = {'qzid':fields.Integer, 'title':fields.String, 'difficulty_level':fields.String, 'text':fields.String, 'no_ques':fields.Integer } quiz = marshal(query_obj, resource_fields) response = jsonify(quiz=quiz) utls.display_tables() response.status_code = 200 logs.info_(response) return response
def get(self): '''Get all quizzes''' print "_______________________________________________" print "QuizzesAPI get fn: %s" %(request) '''Query from quiz table''' Query_obj = qzdb.Quiz.query.order_by(qzdb.Quiz.qzid).all() import pdb; pdb.set_trace() if not Query_obj: response = handle_invalid_usage(InvalidUsage('Error: No quizzes found',status_code=404)) return response '''Return response''' response_fields = [{'name':'qzid', 'relnshp':False,'subfields':None}, {'name':'title','relnshp':False,'subfields':None}, {'name':'difficulty_level','relnshp':False,'subfields':None}, {'name':'text','relnshp':False,'subfields':None}, {'name':'no_ques','relnshp':False,'subfields':None}] quizzes = utls.serialize_to_json(response_fields, Query_obj) print "Json response" print "=============\n" print '{\'quizzes\':%s}\n' %(quizzes) response = jsonify(quizzes=quizzes) response.status_code = 200 utls.display_tables() return response
def get(self, qzid): """Get result for taker of this quiz""" logs.debug_ ("_________________________________________________") logs.debug_ ("UsrQuizRtAPI get fn: %s" %(request)) userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Find quiz result for session query_obj = models.User.query.filter_by(userid=userid).first() result = query_obj.qzscore # Return response logs.debug_ ("Json response") logs.debug_ ("=============\n") logs.debug_ ("{\'result\':%s}\n" %(result)) response = jsonify (result=result) response.status_code = 200 utls.display_tables() logs.info_(response) return response
def get(self, qzid, qid): """Get question qid for quiz""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuestionAPI get fn: %s" %(request)) userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException( 'Error: No active session for this user found', status_code=404)) return response # Query Question table query_obj = models.Question.query.join(models.Anschoice).filter\ (models.Question.qid == qid,models.Question.qzid == qzid).all() if not query_obj: response = handle_invalid_usage(InvalidUsageException ('Error: Question not found', status_code=404)) return response # Return response ans_fields = {'ans_choice':fields.String, 'correct':fields.Boolean } resource_fields = {'qid':fields.Integer, 'ques_text':fields.String, 'anschoices':fields.Nested(ans_fields) } question = marshal(query_obj, resource_fields) response = jsonify(question=question) response.status_code = 200 logs.info_(response) utls.display_tables() return response
def login(): # POST if request.method == 'POST': error = None """Post """ logs.debug_ ("_______________________________________________") logs.debug_ ("login get fn: %s" %(request)) username = request.form["username"] pwd = request.form["password"] encrypted_pwd = bcrypt.generate_password_hash(pwd) user_obj=models.User.query.filter_by(username=username).all() if (not user_obj): user_obj = models.User(username,bcrypt.\ generate_password_hash(pwd)) models.db.session.add(user_obj) models.db.session.commit() # Create Flask session if 'username' not in session: session['username'] = username # Return response utls.display_tables() location = "/quizzes" response = make_response(render_template('login.html', error=error), 303) response.location=location return response
def db_init(): db.drop_all() db.create_all() qz1 = Quiz( "Python Basics ", "Simple ", "Explanation", 2) qz2 = Quiz( "Python Advanced", "Moderate", "No text ") db.session.add(qz1) db.session.add(qz2) db.session.commit() ques1 = Question("What does 'def foo(): pass do", "A fn which does nothing",1) ques2 = Question("Is python an OOP l ", "Yes python is an OOP l",1) db.session.add(ques1) db.session.add(ques2) db.session.commit() ans1 = Anschoice(1, 1, "a. This function does nothing ", True) ans2 = Anschoice(1, 1, "b. This function returns a fn pass ", False) ans3 = Anschoice(1, 1, "c. This function is not yet defined", False) ans4 = Anschoice(1, 2, "a. Yes Python is object oriented ", True) ans5 = Anschoice(1, 2, "b. No Python is not object oriented", False) ans6 = Anschoice(1, 2, "c. Python may not be used as OOP l ", True) db.session.add(ans1) db.session.add(ans2) db.session.add(ans3) db.session.add(ans4) db.session.add(ans5) db.session.add(ans6) db.session.commit() utls.display_tables() return None
def quiz_result(qzid, userid): # GET /user/quizzes/{qzid}/result if ((request.method == 'GET') or (request.method == 'POST')): error = None """Get result for taker of this quiz""" logs.debug_ ("_________________________________________________") logs.debug_ ("UsrQuizRtAPI get fn: %s" %(request)) # get user id for user - in this case just create default? userid = 1 qzid = 1 # Find quiz result for session query_obj = models.User.query.filter_by(userid=userid).first() score = query_obj.qzscore utls.display_tables() # Return response location = "/quizzes/%d/%d/result" % (qzid , userid) response = make_response(render_template('result.html', userid=userid, qzid=qzid, score=score, error=error), 200) response.location=location return response
def login(): # POST if request.method == 'POST': error = None """Post """ logs.debug_("_______________________________________________") logs.debug_("login get fn: %s" % (request)) username = request.form["username"] pwd = request.form["password"] encrypted_pwd = bcrypt.generate_password_hash(pwd) user_obj = models.User.query.filter_by(username=username).all() if (not user_obj): user_obj = models.User(username,bcrypt.\ generate_password_hash(pwd)) models.db.session.add(user_obj) models.db.session.commit() # Create Flask session if 'username' not in session: session['username'] = username # Return response utls.display_tables() location = "/quizzes" response = make_response(render_template('login.html', error=error), 303) response.location = location return response
def db_init(): db.drop_all() db.create_all() qz1 = Quiz( "Python Basics", "Simple", "This quiz tests you on various fundamentals", 2) qz2 = Quiz( "Python Advanced", "Moderate", "No text") db.session.add(qz1) db.session.add(qz2) db.session.commit() ques1 = Question("What does the following code do? def foo(): pass", "You can define a function in python which does nothing",1) ques2 = Question("Is python an Object oriented programming language?", "Yes python is an OOP language",1) db.session.add(ques1) db.session.add(ques2) db.session.commit() ans1 = Anschoice(1, 1, "a. This function does nothing", True) ans2 = Anschoice(1, 1, "b. This function returns a function called pass", False) ans3 = Anschoice(1, 1, "c. This function is not yet defined. It will give error", False) ans4 = Anschoice(1, 2, "a. Yes Python is object oriented", True) ans5 = Anschoice(1, 2, "b. No Python is not object oriented", False) ans6 = Anschoice(1, 2, "c. Python may or may not be used as an object oriented language", True) db.session.add(ans1) db.session.add(ans2) db.session.add(ans3) db.session.add(ans4) db.session.add(ans5) db.session.add(ans6) db.session.commit() utls.display_tables() return None
def get(self, qzid, qid): '''Get question qid for quiz''' print "_________________________________________________" print "QuestionAPI get fn: %s" %(request) '''Query Question table''' Query_obj = qzdb.Question.query.join(qzdb.Anschoice).filter(qzdb.Question.qid == qid,qzdb.Question.qzid == qzid).all() if not Query_obj: response = handle_invalid_usage(InvalidUsage('Error: Question not found',status_code=404)) return response '''Return response''' response_fields = [{'name':'qid', 'relnshp':False, 'subfields':None}, {'name':'ques_text', 'relnshp':False, 'subfields':None}, {'name':'ans_text','relnshp':False, 'subfields':None}, {'name':'qzid','relnshp':False, 'subfields':None}, {'name':'anschoices','relnshp':True, 'subfields':[{'name':'ans_choice','relnshp':False,'subfields':None}, {'name':'correct', 'relnshp':False, 'subfields':None}]} ] question = utls.serialize_to_json(response_fields, Query_obj) print "Json response" print "=============\n" print '{\'question\':%s}\n' %(question) response = jsonify(question = question) response.status_code = 200 utls.display_tables() return response
def patch(self, qzid): '''Edit quiz details''' print "_________________________________________________" print "QuizAPI patch fn: %s \nJson Request\n=============\n %s" %(request, request.json) '''Get values from req''' args = self.reqparse.parse_args() cols = {} no_data = True for key, value in args.iteritems(): if value != None: no_data = False cols[key] = request.json[key] '''If no input in patch request, return 400''' if no_data: response = handle_invalid_usage(InvalidUsage('Error: No input data provided in Patch req',status_code=400)) return response '''Update tables''' qzdb.Quiz.query.filter_by(qzid = qzid).update(cols) qzdb.db.session.commit() '''Return response''' Query_obj = qzdb.Quiz.query.filter_by(qzid=qzid).all() resp_fields = ['qzid','title', 'difficulty_level', 'text','no_ques'] relnshp_flag = 0 quiz = utls.serialize_to_json(resp_fields, Query_obj, relnshp_flag) print "Json response" print "=============\n" print '{\'quiz\':%s\n}' %(quiz) response = jsonify(quiz=quiz) response.status_code = 200 utls.display_tables() return response
def api(): # GET / if request.method == 'GET': app.logger.info(request) err="" utls.display_tables() return render_template('api.html',err=err)
def patch(self, qzid): """Edit quiz details""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuizAPI patch fn: %s \nJson Request\n=============\n %s" %(request, request.json)) userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Get values from req args = self.reqparse.parse_args() cols = {} no_data = True for key, value in args.iteritems(): if value is not None: no_data = False cols[key] = request.json[key] # Check if user is auth to update this quiz query_obj = models.Quiz.query.filter_by(qzid=qzid).first() if (query_obj.userid != userid): response = handle_invalid_usage(InvalidUsageException ('Error: Unauthorized Username for this quiz', \ status_code=401)) return response # If no input in patch request, return 400 if no_data: response = handle_invalid_usage(InvalidUsageException ('Error: No input data provided in Patch req', status_code=400)) return response # Update tables models.Quiz.query.filter_by(qzid=qzid).update(cols) models.db.session.commit() # Return response query_obj = models.Quiz.query.filter_by(qzid=qzid).all() resource_fields = {'qzid':fields.Integer, 'title':fields.String, 'difficulty_level':fields.String, 'text':fields.String, 'no_ques':fields.Integer } quiz = marshal(query_obj, resource_fields) response = jsonify(quiz=quiz) response.status_code = 200 logs.info_(response) utls.display_tables() return response
def patch(self, ideaid): """Edit idea details""" logs.debug_ ("_________________________________________________") logs.debug_ ("IdeaAPI patch fn: %s \nJson Request\n=============\n %s" %(request, request.json)) userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Get values from req args = self.reqparse.parse_args() cols = {} no_data = True for key, value in args.iteritems(): if value is not None: no_data = False cols[key] = request.json[key] # Check if user is auth to update this idea query_obj = models.Idea.query.filter_by(ideaid=ideaid).first() if (query_obj.userid != userid): response = handle_invalid_usage(InvalidUsageException ('Error: Unauthorized Username for this idea', \ status_code=401)) return response # If no input in patch request, return 400 if no_data: response = handle_invalid_usage(InvalidUsageException ('Error: No input data provided in Patch req', status_code=400)) return response # Update tables models.Idea.query.filter_by(ideaid=ideaid).update(cols) models.db.session.commit() # Return response query_obj = models.Idea.query.filter_by(ideaid=ideaid).all() resource_fields = {'ideaid':fields.Integer, 'title':fields.String, 'score':fields.String, 'text':fields.String, 'no_ques':fields.Integer } idea = marshal(query_obj, resource_fields) response = jsonify(idea=idea) response.status_code = 200 logs.info_(response) utls.display_tables() return response
def post(self, qzid): '''Add question to quiz''' print "_________________________________________________" print "QuestionsAPI post fn: %s \nJson Request\n=============\n %s" %(request, request.json) '''Get data from req''' args = self.reqparse.parse_args() for key, value in args.iteritems(): if value != None: if (key == 'ques_text'): ques_text = request.json['ques_text'] if (key == 'ans_text'): ans_text = request.json['ans_text'] if (key == 'anschoices'): anschoices = request.json['anschoices'] '''Post new data to table''' qn_obj = qzdb.Question(ques_text, ans_text, qzid) qzdb.db.session.add(qn_obj) '''Update correspnoding relationship tables ''' #Quiz table L = qzdb.Quiz.query.filter_by(qzid = qzid).first() qzdb.Quiz.query.filter_by(qzid = qzid).update(dict(no_ques= (L.no_ques+1))) #Ans choices table ansidL = [] for i in range(len(anschoices)): ans_obj = qzdb.Anschoice(qzid, qn_obj.qid, anschoices[i]["answer"], anschoices[i]["correct"] ) qzdb.db.session.add(ans_obj) qzdb.db.session.commit() '''Return response''' location = "/api/quizzes/"+str(qzid)+"/questions/"+str(qn_obj.qid) Query_obj = qzdb.Question.query.join(qzdb.Anschoice).filter(qzdb.Question.qid == qn_obj.qid).all() response_fields = [{'name':'ques_text', 'relnshp':False, 'subfields':None}, {'name':'ans_text','relnshp':False, 'subfields':None}, {'name':'qzid','relnshp':False, 'subfields':None}, {'name':'anschoices','relnshp':True, 'subfields':[{'name':'ans_choice','relnshp':False,'subfields':None}, {'name':'correct', 'relnshp':False, 'subfields':None}]} ] question = utls.serialize_to_json(response_fields, Query_obj, 0) print "Json response" print "=============\n" print '{\'question\':%s}\n' %(question) response = jsonify(question = question) response.location = location response.status_code = 201 utls.display_tables() return response
def users(): # GET if request.method == 'GET': app.logger.info(request) err="" user_obj = models.User.query.all() if not user_obj: err="No user" utls.display_tables() response = render_template('list_of_users.html', user_obj=user_obj, err=err ) return response # POST if request.method == 'POST': app.logger.info(request) err="" username = request.form["username"] email = request.form["email"] address = request.form["address"] podcast1 = request.form["podcast1"] podcast2 = request.form["podcast2"] podcast3 = request.form["podcast3"] user_obj = models.User.query.filter_by(username=username).all() if (not user_obj): user_obj = models.User(username,email,address) models.db.session.add(user_obj) query_obj = models.User.query.filter_by(username=username).first() userid = query_obj.userid if (podcast1): pod_obj1 = models.Podcast(podcast1,userid) models.db.session.add(pod_obj1) if (podcast2): pod_obj2 = models.Podcast(podcast2, userid) models.db.session.add(pod_obj2) if (podcast3): pod_obj3 = models.Podcast(podcast3, userid) models.db.session.add(pod_obj3) models.db.session.commit() else: err = "User already exists" utls.display_tables() response = render_template('api.html', user_obj=user_obj, err=err) return response
def patch(self, qzid, qid): '''Add question to quiz''' print "_________________________________________________" print "QuestionAPI patch fn: %s \nJson Request\n=============\n %s" %(request, request.json) '''Check if question qid exists for qzid, raise error''' Query_obj = qzdb.Question.query.filter(qzdb.Question.qid == qid,qzdb.Question.qzid == qzid).all() if not Query_obj: response = handle_invalid_usage(InvalidUsage('Error: Question to edit not found for quiz',status_code=400)) return response args = self.reqparse.parse_args() for key, value in args.iteritems(): if value != None: if (key == 'ques_text'): ques_text = request.json['ques_text'] if (key == 'ans_text'): ans_text = request.json['ans_text'] if (key == 'anschoices'): anschoices = request.json['anschoices'] '''Update all table entries with input data''' qzdb.Question.query.filter_by(qid = qid).update(dict(ques_text=ques_text, ans_text=ans_text)) '''Updating correspnoding relationship tables ''' #Ans choices table Q_obj = qzdb.Anschoice.query.filter_by(qid = qid) index = 0 for i in Q_obj: ansid = Q_obj[index].ansid ans_choice = anschoices[index]["answer"] correct = anschoices[index]["correct"] qzdb.Anschoice.query.filter_by(ansid = ansid).update(dict(ans_choice = ans_choice, correct = correct)) index += 1 qzdb.db.session.commit() '''Return response''' Query_obj = qzdb.Question.query.join(qzdb.Anschoice).filter(qzdb.Question.qid == qid).all() response_fields = [{'name':'qid', 'relnshp':False, 'subfields':None}, {'name':'ques_text', 'relnshp':False, 'subfields':None}, {'name':'ans_text','relnshp':False, 'subfields':None}, {'name':'qzid','relnshp':False, 'subfields':None}, {'name':'anschoices','relnshp':True, 'subfields':[{'name':'ans_choice','relnshp':False,'subfields':None}, {'name':'correct', 'relnshp':False, 'subfields':None}]} ] question = utls.serialize_to_json(response_fields, Query_obj) print "Json response" print "=============\n" print '{\'question\':%s\n}' %(question) response = jsonify(question=question) response.status_code = 200 utls.display_tables() return response
def post(self): """Login already existing user or add new user""" print "-------Hello" logs.debug_ ("_________________________________________________") logs.debug_ ("UserAPI post fn: %s\nJson Request\n=============\n %s" %(request, request.json)) # Get values from request args = self.reqparse.parse_args() for key, value in args.iteritems(): if value is not None: if (key == 'username'): username = request.json['username'] if (key == 'password'): password = request.json['password'] # Check and Update tables # This is implemented as if we are processing get /users user_obj = models.User.query.filter_by(username=username).first() user_index = None for i in range(len(user_obj)): if username in user_obj[i].username: user_index = i if user_index is not None: #match encrypted password with one in table if not bcrypt.check_password_hash(user_obj[user_index].password, password): response = handle_invalid_usage(InvalidUsageException ('Error: Password for user does not match', status_code=401)) return response else: # Add new user user_obj = models.User(username, bcrypt.generate_password_hash(password)) models.db.session.add(user_obj) models.db.session.commit() # Create flask session here with secret key based on username if 'username' not in session: session['username'] = username # Return response location = "/users/%s" % user_obj.userid query_obj = models.User.query.filter_by(userid=user_obj.userid).all() resource_fields = {'userid':fields.Integer} user = marshal(query_obj, resource_fields) response = jsonify(user=user) response.status_code = 201 response.location = location logs.info_(response) utls.display_tables() return response
def index(): # GET / if request.method == 'GET': error = None """Get index.html""" logs.debug_("_______________________________________________") logs.debug_("index.html get fn: %s" % (request)) # Return response utls.display_tables() return render_template('login.html', error=error)
def logout(): # GET / error = None logs.debug_("_______________________________________________") logs.debug_("QuizzesAPI post fn: %s" % (request)) session.pop('username', None) # Return response utls.display_tables() return render_template('logout.html', error=error)
def index(): # GET / if request.method == 'GET': error = None """Get index.html""" logs.debug_ ("_______________________________________________") logs.debug_ ("index.html get fn: %s" %(request)) # Return response utls.display_tables() return render_template('login.html', error=error)
def logout(): # GET / error = None logs.debug_ ("_______________________________________________") logs.debug_ ("QuizzesAPI post fn: %s" %(request)) session.pop('username',None) # Return response utls.display_tables() return render_template('logout.html', error=error)
def delete(self): """Delete session""" logs.debug_ ("_________________________________________________") logs.debug_ ("SessionAPI del fn: %s" %(request.url)) # Pop user from session userid, username = utls.get_user_from_hdr() if 'username' not in session: logs.debug_("User already not in session") else: session.pop('username', None) # Return response utls.display_tables() return 204
def post(self): """Add new quiz""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuizzesAPI post fn: %s\nJson Request\n=============\n %s" %(request, request.json)) userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Get values from request args = self.reqparse.parse_args() for key, value in args.iteritems(): if value is not None: if (key == 'title'): title = request.json['title'] if (key == 'difficulty_level'): difficulty_level = request.json['difficulty_level'] if (key == 'text'): text = request.json['text'] # Update tables quiz_obj = models.Quiz(title, difficulty_level, text, userid) models.db.session.add(quiz_obj) models.db.session.commit() # Return response location = "/quizzes/%s" % quiz_obj.qzid query_obj = models.Quiz.query.filter_by(qzid=quiz_obj.qzid).all() resource_fields = {'qzid':fields.Integer, 'title':fields.String, 'difficulty_level':fields.String, 'text':fields.String, 'no_ques':fields.Integer } quiz = marshal(query_obj, resource_fields) response = jsonify(quiz=quiz) response.status_code = 201 response.location = location logs.info_(response) utls.display_tables() return response
def post(self): """Add new idea""" logs.debug_ ("_________________________________________________") logs.debug_ ("IdeasAPI post fn: %s\nJson Request\n=============\n %s" %(request, request.json)) userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Get values from request args = self.reqparse.parse_args() for key, value in args.iteritems(): if value is not None: if (key == 'title'): title = request.json['title'] if (key == 'score'): score = request.json['score'] if (key == 'text'): text = request.json['text'] # Update tables idea_obj = models.Idea(title, score, text, userid) models.db.session.add(idea_obj) models.db.session.commit() # Return response location = "/ideas/%s" % idea_obj.ideaid query_obj = models.Idea.query.filter_by(ideaid=idea_obj.ideaid).all() resource_fields = {'ideaid':fields.Integer, 'title':fields.String, 'score':fields.String, 'text':fields.String, 'no_ques':fields.Integer } idea = marshal(query_obj, resource_fields) response = jsonify(idea=idea) response.status_code = 201 response.location = location logs.info_(response) utls.display_tables() return response
def quizzes(): # GET /quizzes if request.method == 'GET': error = None """Get all quiz questions""" logs.debug_("_______________________________________________") logs.debug_("QuizzesAPI get fn: %s" % (request)) username = session['username'] # Return response utls.display_tables() response = make_response( render_template('welcome.html', username=username, error=error), 200) return response
def get(self, qzid): """Get all questions for quiz""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuestionisAPI get fn: %s" %(request)) # Check if user is auth to get details of this ques userid, username = utls.get_user_from_hdr() query_obj = models.Quiz.query.filter_by(qzid=qzid).first() if (query_obj.userid != userid): response = handle_invalid_usage(InvalidUsageException ('Error: Unauthorized Username for this quiz', \ status_code=401)) return response if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Query from questions table query_obj = models.Question.query.join(models.Quiz).join(models.Anschoice).\ filter(models.Quiz.qzid == qzid).all() if not query_obj: response = handle_invalid_usage(InvalidUsageException ('Error: No question for quiz found', status_code=404)) return response # Return response ans_fields = {'ans_choice':fields.String, 'correct':fields.Boolean } resource_fields = {'qid':fields.Integer, 'ques_text':fields.String, 'ans_text':fields.String, 'qzid':fields.Integer, 'anschoices':fields.Nested(ans_fields) } questions = marshal(query_obj, resource_fields) response = jsonify(questions=questions) response.status_code = 200 utls.display_tables() logs.info_(response) return response
def quizzes(): # GET /quizzes if request.method == 'GET': error = None """Get all quiz questions""" logs.debug_ ("_______________________________________________") logs.debug_ ("QuizzesAPI get fn: %s" %(request)) username = session['username'] # Return response utls.display_tables() response= make_response(render_template('welcome.html', username=username, error=error), 200) return response
def podcasts(userid): # GET if request.method == 'GET': app.logger.info(request) err="" user_obj = models.User.query.join(models.Podcast).filter_by(userid=userid).all() if not user_obj: err="No such user" utls.display_tables() response = render_template('alluserdata.html', user_obj=user_obj, err=err ) return response
def delete(self, qzid): '''Delete quiz''' print "_________________________________________________" print "QuizAPI delete fn: %s" %(request) '''delete all questions table entries for the quiz''' qzdb.Question.query.join(qzdb.Quiz).filter(qzdb.Question.qzid == qzid).delete() '''delete all Ans choices table entries for quiz''' qzdb.Anschoice.query.join(qzdb.Quiz).filter(qzdb.Anschoice.qzid == qzid).delete() '''delete quiz''' qzdb.Quiz.query.filter(qzdb.Quiz.qzid == qzid).delete() qzdb.db.session.commit() '''Return response''' utls.display_tables() return 204
def delete(self, qzid, qid): '''Delete question''' print "_________________________________________________" print "QuestionAPI del fn: %s" %(request.url) '''Updating no_ques col in quiz table''' L = qzdb.Quiz.query.filter_by(qzid = qzid).first() qzdb.Quiz.query.filter_by(qzid = qzid).update(dict(no_ques= (L.no_ques-1))) '''deleting Ans choices table entries for qid''' qzdb.Anschoice.query.filter(qzdb.Anschoice.qid == qid).delete() '''Finally deleting entries from Question table''' qzdb.Question.query.filter_by(qid = qid).delete() qzdb.db.session.commit() '''Return response''' response = jsonify(qid=qid) response.status_code = 204 utls.display_tables() return response
def delete(self, qzid, qid): """Delete question""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuestionAPI del fn: %s" %(request.url)) # Check if user is auth to del this ques userid, username = utls.get_user_from_hdr() query_obj = models.Question.query.filter_by(qid=qid).first() if (query_obj.userid != userid): response = handle_invalid_usage(InvalidUsageException ('Error: Unauthorized Username for this ques', \ status_code=401)) return response if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Updating no_ques col in quiz table L = models.Quiz.query.filter_by(qzid = qzid).first() models.Quiz.query.filter_by(qzid = qzid).\ update(dict(no_ques= (L.no_ques-1))) # Deleting Ans choices table entries for qid models.Anschoice.query.filter(models.Anschoice.qid == qid).delete() # Finally deleting entries from Question table models.Question.query.filter_by(qid = qid).delete() models.db.session.commit() # Return response response = jsonify(qid=qid) response.status_code = 204 logs.info_(response) utls.display_tables() return response
def get(self, qzid, qid): '''Get question qid for quiz''' print "_________________________________________________" print "QuestionAPI get fn: %s" %(request) '''Query Question table''' Query_obj = qzdb.Question.query.join(qzdb.Anschoice).filter(qzdb.Question.qid == qid,qzdb.Question.qzid == qzid).all() if Query_obj == []: response = handle_invalid_usage(InvalidUsage('Error: Question not found',status_code=404)) return response '''Return response''' resp_fields = ['qid', 'qzid','ques_text', 'ans_text', 'anschoices'] relnshp_flag = resp_fields.index('anschoices') question = utls.serialize_to_json(resp_fields, Query_obj, relnshp_flag) print "Json response" print "=============\n" print '{\'question\':%s}\n' %(question) response = jsonify(question = question) response.status_code = 200 utls.display_tables() return response
def get(self): '''Get all quizzes''' print "_______________________________________________" print "QuizzesAPI get fn: %s" %(request) '''Query from quiz table''' Query_obj = qzdb.Quiz.query.order_by(qzdb.Quiz.qzid).all() if Query_obj == []: response = handle_invalid_usage(InvalidUsage('Error: No quizzes found',status_code=404)) return response '''Return response''' resp_fields = ['qzid','title', 'difficulty_level', 'text','no_ques'] relnshp_flag = 0 quizzes = utls.serialize_to_json(resp_fields, Query_obj, relnshp_flag) print "Json response" print "=============\n" print '{\'quizzes\':%s}\n' %(quizzes) response = jsonify(quizzes=quizzes) response.status_code = 200 utls.display_tables() return response
def post(self): '''Add new quiz''' print "_________________________________________________" print "QuizzesAPI post fn: %s\nJson Request\n=============\n %s" %(request, request.json) '''Get values from request''' args = self.reqparse.parse_args() for key, value in args.iteritems(): if value != None: if (key == 'title'): title = request.json['title'] if (key == 'difficulty_level'): difficulty_level = request.json['difficulty_level'] if (key == 'text'): text = request.json['text'] #print args.help '''Update tables''' Quiz_obj = qzdb.Quiz(title, difficulty_level, text) qzdb.db.session.add(Quiz_obj) qzdb.db.session.commit() '''Return response''' location = "/api/quizzes/"+str(Quiz_obj.qzid) Query_obj = qzdb.Quiz.query.filter_by(qzid=Quiz_obj.qzid).all() response_fields = [{'name':'qzid', 'relnshp':False,'subfields':None}, {'name':'title','relnshp':False,'subfields':None}, {'name':'difficulty_level','relnshp':False,'subfields':None}, {'name':'text','relnshp':False,'subfields':None}, {'name':'no_ques','relnshp':False,'subfields':None}] quiz = utls.serialize_to_json(response_fields, Query_obj) print "Json response" print "=============\n" print '{\'quiz\':%s\n}' %(quiz) response = jsonify(quiz=quiz) response.status_code = 201 response.location = location utls.display_tables() return response
def delete(self, ideaid): """Delete idea""" logs.debug_ ("_________________________________________________") logs.debug_ ("IdeaAPI delete fn: %s" %(request)) # Check if user is auth to delete this idea userid, username = utls.get_user_from_hdr() query_obj = models.Idea.query.filter_by(ideaid=ideaid).first() if (query_obj.userid != userid): response = handle_invalid_usage(InvalidUsageException ('Error: Unauthorized Username for this idea', \ status_code=401 ) ) return response if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Delete all questions table entries for the idea models.Question.query.join(models.Idea).filter(models.Question.ideaid == ideaid).\ delete() # Delete all Ans choices table entries for idea models.Anschoice.query.join(models.Idea).filter(models.Anschoice.ideaid == ideaid).\ delete() # Delete idea models.Idea.query.filter(models.Idea.ideaid == ideaid).delete() models.db.session.commit() # Return response utls.display_tables() return 204
def get(self): """Get all ideas""" logs.debug_ ("_______________________________________________") logs.debug_ ("IdeasAPI get fn: %s" %(request)) # Query ideas for this user from idea table # Should that be the case or should user be able to see # other ideas as well userid, username = utls.get_user_from_hdr() query_obj = models.Idea.query.filter_by(userid=userid).all() if not query_obj: response = handle_invalid_usage(InvalidUsageException ('Error: No ideas found', status_code=404)) return response if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Return response resource_fields = {} resource_fields['ideaid'] =fields.Integer resource_fields['title']=fields.String resource_fields['desc']=fields.String resource_fields['score'] =fields.String resource_fields['userid'] =fields.Integer ideas = marshal(query_obj, resource_fields) response = jsonify(ideas=ideas) response.status_code = 200 logs.info_(response) utls.display_tables() return response
def db_init(): models.db.drop_all() models.db.create_all() utls.display_tables() #populate Quiz table qz1 = models.Quiz( "Python Basics ", "Simple ", "Explanation", 1, 2) qz2 = models.Quiz( "Python Advanced", "Moderate", "No text ", 1) models.db.session.add_all([qz1,qz2]) #populate models.Questions table #Quiz 1 ques1 = models.Question("What does 'def foo(): pass do", "A fn which does nothing",1,1) ques2 = models.Question("Is python an OOP l ", "Yes python is an OOP l",1,1) ques3 = models.Question("What is operator overloading?", "Operator overloading is a concept in OOPS",1,1) ques4 = models.Question("Is python dynmaically typed? ", "Yes python is a dynmaically typed language",1,1) models.db.session.add_all([ques1, ques2, ques3, ques4]) #Quiz 1 ques5 = models.Question("What is the use of an assertion?", "A fn which does nothing",2,1) ques6 = models.Question("What is python library scrapy used for?", "Yes python is an OOP l",2,1) models.db.session.add_all([ques5, ques6]) #populate Answer choices table #Quiz 1 ans1 = models.Anschoice(1, 1, "(a) This function does nothing ", True) ans2 = models.Anschoice(1, 1, "(b) This function returns a fn pass ", False) ans3 = models.Anschoice(1, 1, "(c) This function is not yet defined", False) ans4 = models.Anschoice(1, 2, "(a) Yes Python is object oriented ", True) ans5 = models.Anschoice(1, 2, "(b) No Python is not object oriented", False) ans6 = models.Anschoice(1, 2, "(c) Python may not be used as OOP l ", False) ans7 = models.Anschoice(1, 3, "(a) This function does nothing ", True) ans8 = models.Anschoice(1, 3, "(b) This function returns a fn pass ", False) ans9 = models.Anschoice(1, 3, "(c) This function is not yet defined", False) ans10 = models.Anschoice(1, 4, "(a) Yes Python is object oriented ", True) ans11 = models.Anschoice(1, 4, "(b) No Python is not object oriented", False) ans12 = models.Anschoice(1, 4, "(c) Python may not be used as OOP l ", False) models.db.session.add_all([ans1, ans2, ans3, ans4, ans5, ans6, ans7, ans8,\ ans9, ans10, ans11, ans12]) #Quiz 2 ans13 = models.Anschoice(2, 5, "(a) This function does nothing ", False) ans14 = models.Anschoice(2, 5, "(b) This function returns a fn pass ", True) ans15 = models.Anschoice(2, 5, "(c) This function is not yet defined", False) ans16 = models.Anschoice(2, 6, "(a) Yes Python is object oriented ", False) ans17 = models.Anschoice(2, 6, "(b) No Python is not object oriented", True) ans18 = models.Anschoice(2, 6, "(c) Python may not be used as OOP l ", False) models.db.session.add_all([ans13, ans14, ans15, ans16, ans17, ans18]) try: models.db.session.commit() except IntegrityError: print "Arch: Caught SQL Alchemy exception Integrity Error" except InvalidRequestError: print "Arch: Caught SQL Alchemy exception InvalidRequestError" return None
def post(self, qzid): """Add question to quiz""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuestionsAPI post fn: %s \nJson Request\n=============\n %s" %(request, request.json)) # Get userid from hdr userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Get data from req args = self.reqparse.parse_args() for key, value in args.iteritems(): if value is not None: if (key == 'ques_text'): ques_text = request.json['ques_text'] if (key == 'ans_text'): ans_text = request.json['ans_text'] if (key == 'anschoices'): anschoices = request.json['anschoices'] # Post new data to table qn_obj = models.Question(ques_text, ans_text, qzid, userid) models.db.session.add(qn_obj) # Update correspnoding relationship tables #Quiz table L = models.Quiz.query.filter_by(qzid = qzid).first() models.Quiz.query.filter_by(qzid = qzid).update(dict(no_ques= (L.no_ques+1))) # Ans choices table ansidL = [] for choice in range(len(anschoices)): ans_obj = models.Anschoice(qzid, qn_obj.qid, anschoices[choice]["answer"], anschoices[choice]["correct"] ) models.db.session.add(ans_obj) models.db.session.commit() # Return response location = "/quizzes/%s/questions/%s" % (qzid, qn_obj.qid) query_obj = models.Question.query.join(models.Anschoice).\ filter(models.Question.qid == qn_obj.qid).all() qid = qn_obj.qid ans_fields = {'ans_choice':fields.String, 'correct':fields.Boolean } resource_fields = {'ques_text':fields.String, 'ans_text':fields.String, 'qzid':fields.Integer, 'qid':fields.Integer, 'anschoices':fields.Nested(ans_fields) } question = marshal(query_obj, resource_fields) response = jsonify(question=question) response.location = location response.status_code = 201 logs.info_(response) utls.display_tables() return response
def patch(self, qzid, qid): """Add question to quiz""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuestionAPI patch fn: %s \nJson Request\n=============\n %s" %(request, request.json)) # Check if user is auth to update this ques userid, username = utls.get_user_from_hdr() query_obj = models.Question.query.filter_by(qid=qid).first() if (query_obj.userid != userid): response = handle_invalid_usage(InvalidUsageException ('Error: Unauthorized Username for this ques', \ status_code=401)) return response if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Check if question qid exists for qzid, raise error query_obj = models.Question.query.filter(models.Question.qid == qid,models.Question.qzid == qzid).all() if not query_obj: response = handle_invalid_usage(InvalidUsageException ('Error: Question to edit not found for ques', status_code=400)) return response args = self.reqparse.parse_args() for key, value in args.iteritems(): if value is not None: if (key == 'ques_text'): ques_text = request.json['ques_text'] if (key == 'ans_text'): ans_text = request.json['ans_text'] if (key == 'anschoices'): anschoices = request.json['anschoices'] # Update all table entries with input data models.Question.query.filter_by(qid = qid).\ update(dict(ques_text=ques_text, ans_text=ans_text)) # Updating correspnoding relationship tables # Ans choices table query_obj = models.Anschoice.query.filter_by(qid = qid) index = 0 for choice in query_obj: ansid = query_obj[index].ansid ans_choice = anschoices[index]["answer"] correct = anschoices[index]["correct"] models.Anschoice.query.filter_by(ansid = ansid).\ update(dict(ans_choice = ans_choice, correct = correct)) index += 1 models.db.session.commit() # Return response query_obj = models.Question.query.join(models.Anschoice).filter( models.Question.qid == qid).all() ans_fields = {'ans_choice':fields.String, 'correct':fields.Boolean } resource_fields = {'qid':fields.Integer, 'ques_text':fields.String, 'ans_text':fields.String, 'qzid':fields.Integer, 'anschoices':fields.Nested(ans_fields) } question = marshal(query_obj, resource_fields) response = jsonify(question=question) response.status_code = 200 logs.info_(response) utls.display_tables() return response
def post(self, qzid, qid): """Answer question of quiz""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuestionAPI patch fn: %s \nJson Request\n=============\n %s" %(request, request.json)) # Check if cookie user_session exists userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException( 'Error: No active session found for this user', status_code=404)) return response # Check if question qid exists for qzid, raise error query_obj = models.Question.query.filter( models.Question.qid == qid,models.Question.qzid == qzid).all() if not query_obj: response = handle_invalid_usage(InvalidUsageException ('Error: Question to edit not found for ques', status_code=400)) return response args = self.reqparse.parse_args() for key, value in args.iteritems(): if value is not None: if (key == 'anschoices'): anschoices = request.json['anschoices'] # Comparing quiz taker answers with actual ans choices in db correct = True query_obj = models.Anschoice.query.filter_by(qid=qid).all() index = 0 for choice in query_obj: if (unicode(query_obj[index].correct) != anschoices[index]["correct"]): correct = False index += 1 if correct: #update the user table in the database query_obj = models.User.query.filter_by(userid=userid).all() cur_qzscore= query_obj[0].qzscore #get current quiz score #increment quiz score models.User.query.filter_by(userid=userid).\ update(dict(qzscore=cur_qzscore+1)) query_obj = models.Question.query.join(models.Anschoice).filter\ (models.Question.qid == qid).all() location = "/quizzes/<int:qzid>/result %s" % qzid # Return response ans_fields = {'ans_choice':fields.String, 'correct':fields.Boolean } resource_fields = {'qid':fields.Integer, 'ques_text':fields.String, 'ans_text':fields.String, 'qzid':fields.Integer, 'anschoices':fields.Nested(ans_fields) } question = marshal(query_obj, resource_fields) response = jsonify(question=question) response.status_code = 200 response.location = location logs.info_(response) utls.display_tables() return response
def quiz_questions(qzid): # GET /quizzes/qzid/questions if request.method == 'GET': error = None """Get all quiz questions""" logs.debug_("_______________________________________________") logs.debug_("QuizzesAPI get fn: %s" % (request)) # Query Question table ques = models.Question.query.join(models.Anschoice).filter\ (models.Question.qzid == qzid).all() # Return response utls.display_tables() return render_template('questions.html', ques=ques, error=error) #POST /quizzes/qzid/questions else: error = None """ Post answers to all quiz questions""" logs.debug_("_______________________________________________") logs.debug_("QuizzesAPI Post fn: %s" % (request)) #get all questions from db ques_obj = models.Question.query.join(models.Anschoice).filter\ (models.Question.qzid == qzid).all() #User must tick one checkbox per ques and only one ansidlist = request.form.getlist("choices") #Getting a list of qid, ansid answeres- [[qid, ansid, anstext],...] qanslist = [] for i in range(len(ques_obj)): tmplist = ansidlist[i].encode('utf-8').split(',') qanslist.append([int(tmplist[0]), int(tmplist[1]), tmplist[2]]) # Just for testing setting userid = 1 username = session['username'] user_obj = models.User.query.filter_by(username=username).first() userid = user_obj.userid #Check the attempt no for the quiz taker qzattemptid_obj = models.QResult.query.with_entities(\ sqlalchemy.func.max(models.QResult.qzattemptid)).\ filter_by(qzid=qzid, userid=userid).first() if (qzattemptid_obj == (None, )): qzattemptid = 1 else: qzattemptid = qzattemptid_obj[0] + 1 #Check quiz taker's answers against ones in the table qindex = 0 Resultlist = [] for index in range(len(qanslist)): qid = qanslist[index][0] qscore = 0 for ans in ques_obj[index].anschoices: if ((ans.qid == qanslist[index][0]) and (ans.ansid == qanslist[index][1]) and (ans.correct == True)): #Correct ans increment score qscore = 1 #Update results table with qz question score for user with timestmp Resultlist.append(models.QResult(userid, qzid, qid, qzattemptid, \ qscore)) models.db.session.add_all(Resultlist) models.db.session.commit() utls.display_tables() # Return response response = make_response( render_template('answers.html', ques_obj=ques_obj, qzid=qzid, qanslist=qanslist, error=error), 200) return response
logs.debug_ ("SessionAPI del fn: %s" %(request.url)) # Pop user from session userid, username = utls.get_user_from_hdr() if 'username' not in session: logs.debug_("User already not in session") else: session.pop('username', None) # Return response utls.display_tables() return 204 api.add_resource(UserIdeasAPI, '/user/ideas') api.add_resource(UserIdeaAPI, '/user/ideas/<int:ideaid>') api.add_resource(UsersAPI, '/users') api.add_resource(SessionAPI, '/session') if __name__ == '__main__': #Initial config for db, this can be disabled models.db_init() utls.display_tables() app.debug = True app.run('127.0.0.1', 5004)