Пример #1
0
    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
Пример #2
0
    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
Пример #3
0
    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
Пример #4
0
    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
Пример #5
0
    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
Пример #6
0
    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
Пример #7
0
    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
Пример #8
0
    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
Пример #9
0
    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
Пример #10
0
    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
Пример #11
0
    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
Пример #12
0
    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
Пример #13
0
    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
Пример #14
0
    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
Пример #15
0
    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
Пример #16
0
    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
Пример #17
0
    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
Пример #18
0
    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
Пример #19
0
    def get(self, ideaid):
        """Get idea details"""
        logs.debug_ ("_________________________________________________")
        logs.debug_ ("IdeaAPI get fn: %s" %(request))

        # Check if user is auth to get details of 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

        # Query from idea table
        query_obj = models.Idea.query.filter_by(ideaid = ideaid).all()
        if not query_obj:
            response = handle_invalid_usage(InvalidUsageException
                    ('Error: Idea not found', status_code=404))
            return response

        # Return response
        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)
        return response
Пример #20
0
    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
Пример #21
0
    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
Пример #22
0
    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
Пример #23
0
    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
Пример #24
0
    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
Пример #25
0
    def post(self):
        """Login already existing user or add new user"""
        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']
                if (key == 'role'):
                    role = request.json['role']

        if ((role != 'admin') and  (role != 'user')):
            response = handle_invalid_usage(InvalidUsageException
                        ('Error: Role should be admin or user', \
                         status_code=400))
            return response

        # Check and Update tables
        # This is implemented as if we are processing get /users
        user_obj = models.User.query.filter_by(username=username).all()
        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), 
                                 role)
            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
Пример #26
0
    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
Пример #27
0
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    logs.info_ (response)
    return response
Пример #28
0
    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
Пример #29
0
    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
Пример #30
0
    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
Пример #31
0
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    logs.info_ (response)
    return response