Пример #1
0
    def post(self):
        j = request.get_json()

        # need to ensure the required fields are in the json

        if "question_title" not in j:
            abort(422, message="question_title is not in json body")
        else:
            question_title = j["question_title"]

        if "author" not in j:
            abort(422, message="author not in json body")
        else:
            author = j["author"]

        if "description" not in j:
            abort(422, message="description not in json body")
        else:
            description = j["description"]

        question_obj = Question(
            question_title=question_title,
            author=author,
            description=description,
        )

        d = question_obj.save()

        return json.loads(d.to_json())
Пример #2
0
    def question_respond(self):
        _id = bottle.request.POST.get('_id')
        option_id = bottle.request.POST.get('option')

        if _id and option_id:
            q = Question(_DBCON, _id=_id)
            r = Response(_DBCON)
            r.option = option_id
            r.userId = bottle.request.session.userid
            
            q.responses.append(r)
            q.save()
        
        return bottle.redirect(settings.BASEURL +'/')
Пример #3
0
    def makeKeys(self, filename):
        pollName = ""
        questionName = ""
        answers = []
        polls = []
        questions = []
        question = ""
        pollID = 0
        questionID = 0
        file = open(self.directory + "/" + filename, "r")
        lines = file.readlines()

        for line in lines:
            if line == "\n":
                continue
            elif line[0:8] == "You have":
                pollCount = 15
            elif line[0:5] == "Title":
                title = line[6:]
            elif line[1:5] == "Poll":
                pollID = int(line.split(":")[0].split()[1]) - 1
                polls.append(Poll(line.split(":")[1].split("\t")[0], []))
            elif line[0].isdigit():
                questionID = int(line.split(".")[0]) - 1
                polls[pollID].addToQuestionList(
                    Question(line.split(".")[1][1:]))

            elif line[0:6] == "Answer":
                polls[pollID].questionlist[questionID].appendToKeys(
                    Key(line.split(":")[1][1:-1]))
        return polls
Пример #4
0
    def resolve_export_answers(cls, _, info, tour_id, username):
        if UserModel.objects(username=username):
            user = UserModel.objects.get(username=username)
            if TourModel.objects(id=tour_id):
                tour = TourModel.objects.get(id=tour_id)
                report = 'Antworten für den Nutzer {} im Rundgang {}.\n'.format(
                    user.username, tour.name)
                questions = QuestionModel.objects(tour=tour)
                for question in questions:
                    if AnswerModel.objects(user=user, question=question):
                        answer = AnswerModel.objects.get(user=user,
                                                         question=question)
                        if type(answer) == MCAnswerModel:
                            text_answers = []
                            for index in answer.answer:
                                text_answers.append(
                                    question.possible_answers[index])
                            report = report + 'Frage: {}\n'.format(
                                question.question)
                            for ta in text_answers:
                                report = report + 'Antwort: {}'.format(
                                    ta) + '\n'

                        else:
                            report = report + 'Frage: {}\n Antwort: {}\n'.format(
                                question.question, answer.answer)

                return report
        return ""
Пример #5
0
 def resolve_answers_to_question(cls, _, info, question_id):
     if QuestionModel.objects(id=question_id):
         question = QuestionModel.objects.get(id=question_id)
         user = UserModel.objects.get(username=get_jwt_identity())
         if question.tour.owner == user:
             return list(AnswerModel.objects(question=question))
     return []
Пример #6
0
 def resolve_answer(cls, _, info, question_id):
     if QuestionModel.objects(id=question_id):
         question = QuestionModel.objects.get(id=question_id)
         user = UserModel.objects.get(username=get_jwt_identity())
         return [AnswerModel.objects.get(question=question, user=user)]
     else:
         return []
Пример #7
0
async def quizzes(req, resp):
    if 'quizz-token' in req.headers:
        # Check if user is authenticated and admin if method is not get
        if check_token(req.headers['quizz-token'], False, False if req.method == 'get' else True):
            if req.method == 'get':
                # Return all quizzes
                resp.status_code = api.status_codes.HTTP_200
                resp.media = {'quizzes': json.loads(Quizz.objects.all().to_json())}
            elif req.method == 'post':
                try:
                    questions = []
                    # Get data from request
                    data = await req.media()
                    # Get all questions from array of id
                    for question_id in data['questions']:
                        if Question.objects(id=question_id):
                            quizz_answer = Question.objects.get(id=question_id)
                            questions.append(quizz_answer)
                        else:
                            resp.status_code = api.status_codes.HTTP_401
                            resp.media = {'message': f'Question with the id : {question_id} does not exist'}
                    # Check if more than 2 questions
                    if len(questions) >= 2:
                        # Check if data sent has all informations needed
                        if 'title' in data and 'description' in data and 'image' in data:
                            # Get the user to put in created_by
                            user = User.objects.get(token=req.headers['quizz-token'])
                            # Create quizz
                            new_quizz = Quizz(title=data['title'], description=data['description'], image=data['image'], questions=questions, created_by=user)
                            new_quizz.save(validate=True)
                            # Return the new quizz
                            resp.status_code = api.status_codes.HTTP_200
                            resp.media = {'quizz': json.loads(new_quizz.to_json())}
                        else:
                            resp.status_code = api.status_codes.HTTP_401
                            resp.media = {'message': 'Data sent not valid'}
                    else:
                        # Return an error if not 2 questions or more
                        resp.status_code = api.status_codes.HTTP_401
                        resp.media = {'message': 'Not enough questions'}
                except ValidationError as validation_error:
                    # Return an error if data not valid
                    resp.status_code = api.status_codes.HTTP_401
                    resp.media = {'message': validation_error}
            else:
                # Return error if the HTTP Verb is wrong
                resp.status_code = api.status_codes.HTTP_401
                resp.media = {'message': 'Wrong HTTP Verb'}
        else:
            # Return an error if the user is not authenticated
            resp.status_code = api.status_codes.HTTP_403
            resp.media = {'message': 'Not authenticated'}
    else:
        resp.status_code = api.status_codes.HTTP_403
        resp.media = {'message': 'auth token not sent in request'}
Пример #8
0
 def resolve_answers_in_tour(cls, _, info, tour_id):
     if TourModel.objects(id=tour_id):
         tour = TourModel.objects.get(id=tour_id)
         questions = QuestionModel.objects(tour=tour)
         answers = []
         if questions:
             for question in questions:
                 answers.extend(AnswerModel.objects(question=question))
         return answers
     else:
         return []
Пример #9
0
    def question_save(self):
        _id = bottle.request.POST.get('_id')
        t = bottle.request.POST.get('text')
        options = []

        for option in bottle.request.POST.getall('option'):
            o = Option(_DBCON)
            o.text = option
            o.save()
            options.append(o)

        if t and len(t.strip())>0:
            q = Question(_DBCON, _id)
            q.text = t
            q.options = options
            q.save()
        
            return bottle.redirect(settings.BASEURL +'/')
        else:
            self.viewdata.update({'error':'Please complete the form'})
            return self.question()
Пример #10
0
    def get(self):
        try:
            questions = json.loads(Question.objects().to_json())
            for question in questions:
                answers = json.loads(
                    Answer.objects(
                        question_title=question['question_title']).to_json())
                question['answers'] = answers
        except Exception as e:
            print(e)
            abort(404, message="No questions available")

        return questions
Пример #11
0
 def createSubmitForStudent(self, line):
     length = len(line)
     submit = Submit()
     questions = []
     submit.date = line[3].split(",")[0]
     for i in range(4, length, 2):
         question = Question(line[i])
         keyStrings = line[i + 1].split(";")
         for keyString in keyStrings:
             question.keys.append(StudentAnswer(keyString))
         questions.append(question)
     submit.studentQuestions = questions
     return submit
Пример #12
0
def seed_question():
    from models.Question import Question
    from validation_schemas.QuestionSchema import QuestionSchema
    import json
    
    with open(os.path.join(directory, 'dumps/questions.json')) as f:
        questions = json.load(f)
        for question in questions:
            # will ensure that answer_as_query is syntactically correct
            validated_data = QuestionSchema().load(question)
            db.session.add(Question(**validated_data))
            print("added")
        db.session.commit()
    def mutate(cls, _, info, object_id):
        if get_jwt_claims() == admin_claim:
            if MuseumObjectModel.objects(object_id=object_id):
                museum_object = MuseumObjectModel.objects.get(
                    object_id=object_id)
                pictures = museum_object.picture
                # delete associated pictures
                for picture in pictures:
                    picture.delete()
                # delete object from user favourites
                favourites = FavouritesModel.objects(
                    favourite_objects__contains=museum_object)
                for favourite in favourites:
                    objects = favourite.favourite_objects
                    objects.remove(museum_object)
                    favourite.update(set__favourite_objects=objects)
                    favourite.save()
                # delete object reference from questions
                questions = QuestionModel.objects(
                    linked_objects__contains=museum_object)
                for question in questions:
                    linked = question.linked_objects
                    linked.remove(museum_object)
                    question.update(set__linked_objects=linked)
                # delete checkpoints that reference the object
                checkpoints = ObjectCheckpointModel.objects(
                    museum_object=museum_object)
                for checkpoint in checkpoints:
                    # update tour accordingly
                    tour = checkpoint.tour
                    max_idx = tour.current_checkpoints
                    max_idx -= 1
                    # reduce number of current checkpoints
                    tour.update(set__current_checkpoints=max_idx)
                    tour.save()
                    index = checkpoint.index
                    tour_checkpoints = CheckpointModel.objects(tour=tour)
                    # adjust index of later checkpoints in the tour
                    for cp in tour_checkpoints:
                        if cp.index > index:
                            cpidx = cp.index
                            cpidx -= 1
                            cp.update(set__index=cpidx)
                            cp.save()
                    checkpoint.delete()
                museum_object.delete()
            return DeleteMuseumObject(ok=BooleanField(boolean=True))

        else:
            return DeleteMuseumObject(ok=BooleanField(boolean=False))
Пример #14
0
    def getCorrespondingPoll(self, questionList, date, polls):
        poll = None
        if questionList[0] == "Are you attending this lecture?":
            # this is attendance poll
            question = Question(questionList[0])
            attendancePoll = AttendancePoll("attendance", date, [question])

            if attendancePoll not in polls:
                polls.append(attendancePoll)
            poll = attendancePoll

        else:
            for p in polls:
                if p.getQuestionNames().__eq__(questionList):
                    # print(p.name)
                    poll = p
                    break
        return poll
Пример #15
0
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('_id', type=str, help='unique question id')

        args = parser.parse_args()

        try:
            question = json.loads(Question.objects(pk=args['_id']).to_json())
            question = question[0]
            answers = json.loads(
                Answer.objects(
                    question_title=question['question_title']).to_json())
            question['answers'] = answers

        except Exception as e:
            print(e)
            abort(404,
                  message="Question Id {} doesn't exist".format(args['_id']))

        return question
    def get(self):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('name', type=str, help='Question search')
            args = parser.parse_args()
            questions = json.loads(Question.objects().to_json())
        except Exception as e:
            print(e)
            return {}

        titles = [x['question_title'] for x in questions]
        title_choices = process.extract(args['name'], titles)
        title_choices = [x for x in title_choices if x[1] > 50]
        title_list = []

        for x in title_choices:
            for y in questions:
                if y['question_title'] == x[0]:
                    title_list.append(y)

        return jsonify(title_list)
Пример #17
0
    def post(self, dataset):
        parser = reqparse.RequestParser()
        parser.add_argument("id")
        parser.add_argument("question")
        parser.add_argument("procedure")
        args = parser.parse_args()
        args["procedure"] = literal_eval(args["procedure"])

        if not args["id"]:
            question = Question(dataset=dataset, question=args["question"])
            db.db.getDB().session.add(question)
            db.db.getDB().session.commit()
        else:
            question = Question.query.filter_by(id=args["id"]).first()

        if args["procedure"]:
            if not "id" in args["procedure"].keys():
                procedure = Procedure(question=question.id, status="open")
                db.db.getDB().session.add(procedure)
                db.db.getDB().session.commit()
            else:
                procedure = Procedure.query.filter_by(
                    id=args["procedure"]["id"]).first()
                inputs = Input.query.filter_by(procedure=procedure.id)
                inputs.delete()

                outputs = Ouput.query.filter_by(procedure=procedure.id)
                outputs.delete()

            for input in args["procedure"]["input"]:
                new_input = Input(procedure=procedure.id, name=input)
                db.db.getDB().session.add(new_input)

            for output in args["procedure"]["output"]:
                new_output = Output(procedure=procedure.id, name=output)
                db.db.getDB().session.add(new_output)
        db.db.getDB().session.commit()

        return jsonify(procedure)
Пример #18
0
async def questions(req, resp):
    if 'quizz-token' in req.headers:
        # Check the HTTP request method
        if req.method == 'get':
            # Check if user is authenticated
            if check_token(req.headers['quizz-token'], False, True):
                # Get the user
                user = User.objects.get(token=req.headers['quizz-token'])
                resp.status_code = api.status_codes.HTTP_200
                if user.admin == True:
                    resp.media = {'questions': json.loads(Question.objects.all().to_json())}
                else:
                    resp.media = {'questions': json.loads(Question.objects(created_by=user).to_json())}
            # If not, a message will notify the user
            else:
                resp.status_code = api.status_codes.HTTP_403
                resp.media = {'message': 'Not authenticated'}
        elif req.method == 'post':
            # Check if the user is authenticated and is admin
            if check_token(req.headers['quizz-token'], False, True):
                try:
                    data = await req.media()
                    # Check if the question has at least 2 answers and 4 or less answers
                    if len(data['answers']) >= 2 and len(data['answers']) <= 4:
                        if 'question' in data and 'image' in data:
                            answers_not_valid = False
                            for answer in data['answers']:
                                # Check if the answers have the right attributes
                                if 'name' not in answer or 'value' not in answer:
                                    answers_not_valid = True
                                else:
                                    if isinstance(answer['value'], bool) and isinstance(answer['name'], str):
                                        answers_not_valid = False
                                    else:
                                        answers_not_valid = True
                            if not answers_not_valid:
                                # Get the user to put in created_by
                                user = User.objects.get(token=req.headers['quizz-token'])
                                # Create the question
                                new_question = Question(question=data['question'], image=data['image'], answers=data['answers'], created_by=user)
                                new_question.save(validate=True)
                                # Return a successful message to the frontend
                                resp.status_code = api.status_codes.HTTP_200
                                resp.media = {'question': json.loads(new_question.to_json())}
                            else:
                                resp.status_code = api.status_codes.HTTP_401
                                resp.media = {'message': 'data sent is not valid'}
                    else:
                        resp.status_code = api.status_codes.HTTP_401
                        resp.media = {'message': 'A question must have between 2 and 4 answers'}
                # If data sent is not valid
                except ValidationError as validation_error:
                    # Return an error message
                    resp.status_code = api.status_codes.HTTP_401
                    resp.media = {'message': validation_error}
            else:
                # Return an error message if user is not authenticated or admin
                resp.status_code = api.status_codes.HTTP_403
                resp.media = {'message': 'Not authenticated or not admin'}
    else:
        resp.status_code = api.status_codes.HTTP_403
        resp.media = {'message': 'auth token not sent in request'}
Пример #19
0
async def questions_id(req, resp, *, id):
    if 'quizz-token' in req.headers:
        # Check if user is authenticated and admin if method is not get
        if check_token(req.headers['quizz-token'], False, True):
            # Check if question exists
            if Question.objects(id=id):
                # Get the question with the id in the request
                question = Question.objects.get(id=id)
                # Block for get method
                if req.method == 'get':
                    # Return question
                    resp.status_code = api.status_codes.HTTP_200
                    resp.media = {'question': json.loads(question.to_json())}
                # Block for delete method
                elif req.method == 'delete':
                    try:
                        # Delete the question
                        question.delete()
                        # Return the deleted question
                        resp.status_code = api.status_codes.HTTP_200
                        resp.media = {'question': json.loads(question.to_json())}
                    # Return an error if question can't be deleted
                    except Exception as e:
                        resp.status_code = api.status_codes.HTTP_401
                        resp.media = {'message': e}
                # Block for put or patch method
                elif req.method == 'put' or req.method == 'patch':
                    try:
                        # Get the data from the request
                        data = await req.media()
                        # Check if the question has at least 2 answers and 4 or less answers
                        if len(data['answers']) >= 2 and len(data['answers']) <= 4:
                            if 'question' in data and 'image' in data:
                                answers_not_valid = False
                                for answer in data['answers']:
                                    # Check if the answers have the right attributes
                                    if 'name' not in answer or 'value' not in answer:
                                        answers_not_valid = True
                                    else:
                                        if isinstance(answer['value'], bool) and isinstance(answer['name'], str):
                                            answers_not_valid = False
                                        else:
                                            answers_not_valid = True
                                if not answers_not_valid:
                                    question.question = data['question']
                                    question.image = data['image']
                                    question.answers = data['answers']
                                    question.save()
                                    # Return the question if successful
                                    resp.status_code = api.status_codes.HTTP_200
                                    resp.media = {'question': json.loads(question.to_json())}
                                else:
                                    resp.status_code = api.status_codes.HTTP_401
                                    resp.media = {'message': 'data sent is not valid'}
                        else:
                            resp.status_code = api.status_codes.HTTP_401
                            resp.media = {'message': 'A question must have between 2 and 4 answers'}
                    # Throw an error if data wasn't valid
                    except ValidationError as validation_error:
                        resp.status_code = api.status_codes.HTTP_401
                        resp.media = {'message': validation_error}
                else:
                    # Return error if the HTTP Verb is wrong
                    resp.status_code = api.status_codes.HTTP_401
                    resp.media = {'message': 'Wrong HTTP Verb'}
            else:
                # Return an error if the question was not found
                resp.status_code = api.status_codes.HTTP_401
                resp.media = {'message': 'Question was not found'}
        else:
            # Return an error if the user is not authenticated
            resp.status_code = api.status_codes.HTTP_403
            resp.media = {'message': 'Not authenticated'}
    else:
        resp.status_code = api.status_codes.HTTP_403
        resp.media = {'message': 'auth token not sent in request'}
Пример #20
0
async def quizzes_id(req, resp, *, id):
    if 'quizz-token' in req.headers:
        # Check if user is authenticated and admin
        if check_token(req.headers['quizz-token'], False, False if req.method == 'get' else True):
            # Check if the quizz exists
            if (Quizz.objects(id=id)):
                # Get the quizz from the id in the request
                quizz = Quizz.objects.get(id=id)
                if req.method == 'get':
                    questions = []
                    for question in quizz.questions:
                        questions.append({'id': str(question.pk), 'question': question.question, 'image': question.image, 'answers': question.answers})
                    # Returns question
                    resp.status_code = api.status_codes.HTTP_200
                    resp.media = {'id': str(quizz.pk), 'title': quizz.title, 'description': quizz.description, 'image': quizz.image, 'created_by': quizz.created_by.username, 'questions': questions, 'number_participants': quizz.number_participants}
                # Put/Patch method block
                if (req.method == 'put' or req.method == 'patch'):
                    try:
                        questions = []
                        # Get the data from the request
                        data = await req.media()
                        # Update the quizz
                        if 'title' in data and 'description' in data and 'image' in data:
                            quizz.title = data['title']
                            quizz.decription = data['description']
                            quizz.image = data['image']
                        for question_id in data['questions']:
                            if Question.objects(id=question_id):
                                quizz_answer = Question.objects.get(id=question_id)
                                questions.append(quizz_answer)
                            else:
                                resp.status_code = api.status_codes.HTTP_401
                                resp.media = {'message': f'Question with the id : {question_id} does not exist'}
                        if len(questions) >= 2:
                            quizz.questions = questions
                        else:
                            # Return an error if not 2 questions or more
                            resp.status_codes = api.status_codes.HTTP_401
                            resp.media = {'message': 'Not enough questions'}
                        quizz.save()
                        # Return the updated quizz
                        resp.status_code = api.status_codes.HTTP_200
                        resp.media = {'quizz': json.loads(quizz.to_json())}
                    # Catch a validation error
                    except ValidationError as validation_error:
                        # Throw an error
                        resp.status_code = api.status_codes.HTTP_401
                        resp.media = {'message': validation_error}
                elif (req.method == 'delete'):
                    try:
                        print('hello')
                        # Delete the quizz
                        quizz.delete()
                        resp.status_code = api.status_codes.HTTP_200
                        resp.media = {'quizz': json.loads(quizz.to_json())}
                    except Exception as e:
                        # Throw an error if something occured
                        resp.status_code = api.status_codes.HTTP_401
                        resp.media = {'message': e}
            # If quizz doesn't exist, throw an error
            else:
                resp.status_code = api.status_codes.HTTP_401
                resp.media = {'message': 'The quizz couldn\'t be found'}
        # Throw an error if user is not authenticated or an admin
        else:
            resp.status_code = api.status_codes.HTTP_403
            resp.media = {'message': 'Not authenticated or not admin'}
    else:
        resp.status_code = api.status_codes.HTTP_403
        resp.media = {'message': 'auth token not sent in request'}