Exemple #1
0
    def get_random_questions_by_category():
      body = request.get_json()
      previous_questions = body["previous_questions"]
      search_criteria = json.loads(request.data.decode('utf-8'))
      quiz_category_id = search_criteria["quiz_category"]["id"]
 
      try:
        if request.data:
            category_id = search_criteria["quiz_category"]["id"]
        result = {}
        if (('quiz_category' in search_criteria and quiz_category_id) and 'previous_questions' in search_criteria):
          questions_query = Question.query.filter_by(category=search_criteria['quiz_category']['id']).filter(Question.id.notin_(search_criteria["previous_questions"])).all()
          total_question = len(questions_query)
          if total_question > 0:
            result = {
              "success": True,
              "question": Question.format(questions_query[random.randrange(0, total_question)])
            }
          else:
            result = {
              "success": True,
              "question": None
            }
          return jsonify(result)
        else:
          questions_query_all = Question.query.filter(Question.id.notin_(search_criteria["previous_questions"])).all()
          total_question = len(questions_query_all)
          result = {
            "success": True,
            "question": Question.format(questions_query_all[random.randrange(0, total_question)])
          }
          return jsonify(result)     
      except:
        abort(422)
 def get_next_quiz_question(category_id, prev_qn_id):
   questions = Question.query.filter_by(category=category_id).all()
   previous_question = Question.query.get(prev_qn_id)
   if questions and previous_question:
     format_questions = [Question.format(item) for item in questions]
     prev_qn = Question.format(previous_question)
     if (prev_qn["category"] == category_id):
       prv_qn_idx = format_questions.index(prev_qn)
       if prv_qn_idx >= (len(format_questions)-1):
         return jsonify({
           "status": 400,
           "success": False,
           "message":"No more available questions in category"
         }), 400
       else:
         next_qn = format_questions[prv_qn_idx+1]
         return jsonify({
                         'success': True,
                         'status':200,
                         'next_question': next_qn,
                         })
     else:
       abort(400)
   else:
     abort(404)
Exemple #3
0
    def add_new_question():

        question = request.form.get('question', None)
        answer = request.form.get('answer', None)
        difficulty = request.form.get('difficulty', None)
        category = request.form.get('category', None)
        search_term = request.form.get('searchTerm', None)

        if search_term is None:  # We should try to add question

            if question is None:
                abort(400, {'message': 'The question cannot be empty.'})

            if answer is None:
                abort(400, {'message': 'The answer cannot be empty.'})

            if difficulty is None:
                abort(400, {'message': 'The difficulty cannot be empty.'})

            if category is None:
                abort(400, {'message': 'The category cannot be empty.'})

            try:
                question = Question(question, answer, category, difficulty)
                db.session.add(question)
            except:
                abort(422)
            finally:
                db.session.commit()

            response = question.format()
            response['success'] = True
            return jsonify(response)

        else:
            # find the questions that has the search term in them
            # then return them as a pagenated list

            questions = Question.query.filter(
                Question.question.contains(search_term)).all()
            formated_questions = [question.format() for question in questions]
            sublist = paged_list(formated_questions, 1)

            if len(sublist) == 0:
                abort(
                    404, {
                        'message':
                        'Sorry, no question contains what you have searched for.'
                    })

            return jsonify({
                'success': True,
                'questions': sublist,
                'total_questions': len(Question.query.all()),
                'current_category': None
            })
Exemple #4
0
    def get_question_for_quiz():
        if request.data:
            body = request.get_json()
            previous_questions = body.get('previous_questions', [])
            quiz_category = body.get('quiz_category', None)
            try:
                if quiz_category['id'] == 0:
                    questions_query = Question.query.filter(
                        Question.id.notin_(previous_questions)).all()
                else:
                    questions_query = Question.query.filter_by(
                        category=quiz_category['id']).filter(
                            Question.id.notin_(previous_questions)).all()
                length_of_available_question = len(questions_query)
                if length_of_available_question > 0:
                    result = {
                        "success":
                        True,
                        "questions":
                        Question.format(questions_query[random.randrange(
                            0, length_of_available_question)]),
                    }
                else:
                    result = {"success": True, "questions": None}
                return jsonify(result)

            except Exception as e:
                print(e)
                abort(400)

        abort(422)
Exemple #5
0
    def post_question():
        """
        get request input for a new question. Will be rejected if any of the input
        is null or None
        """
        input = request.get_json()
        question = input.get("question")
        answer = input.get("answer")
        category = input.get("category")
        difficulty = input.get("difficulty")

        if not(question and answer and category and difficulty):
            abort(400)
        try:
            question = Question(
                question=question,
                answer=answer,
                category=category,
                difficulty=difficulty
            )
            question.insert()
        except BaseException:
            abort(400)

        return (jsonify({"success": True, "question": question.format()}), 200)
Exemple #6
0
    def add_question():
        # get data for new question
        body = request.get_json()
        question = body.get('question')
        answer = body.get('answer')
        category = body.get('category')
        difficulty = body.get('difficulty')

        #if one of needed information is missing abort with bad request
        if question is None or answer is None or category is None or difficulty is None:
            abort(400)
        else:
            #define new question with given information
            question = Question(question=question,
                                answer=answer,
                                category=category,
                                difficulty=difficulty)
            try:
                #insert question in database
                question.insert()
                #get all questions
                questions = Question.query.all()
                #format all questions
                formatted_questions = [
                    question.format() for question in questions
                ]
                return jsonify({
                    'success': True,
                    'questions': formatted_questions,
                    'total_questions': len(formatted_questions)
                })
            except:
                abort(422)
    def create_question():

        body = request.get_json()

        new_question = body.get('question', None)
        new_answer = body.get('answer', None)
        new_category = body.get('category', None)
        new_difficulty = body.get('difficulty', None)

        try:
            question = Question(question=new_question,
                                answer=new_answer,
                                category=new_category,
                                difficulty=int(new_difficulty))
            question.insert()

            return jsonify({
                'success': True,
                'created_question_id': question.id,
                'questions': question.format(),
                'total_questions': len(Question.query.all())
            })

        except:
            return unprocessable(422)
Exemple #8
0
 def play():
     search_data = request.get_json()
     if search_data:
         if ('quiz_category' in search_data
                 and 'id' in search_data['quiz_category']
                 and 'previous_questions' in search_data):
             category = search_data['quiz_category']['id']
             previous_questions = search_data["previous_questions"]
             if category == 0:
                 questions_query = Question.query.filter(
                     Question.id.notin_(previous_questions)).all()
             else:
                 questions_query = Question.query.filter_by(
                     category=category).filter(
                         Question.id.notin_(previous_questions)).all()
             length_of_available_question = len(questions_query)
             if length_of_available_question > 0:
                 result = {
                     "success":
                     True,
                     "question":
                     Question.format(questions_query[random.randrange(
                         0, length_of_available_question)])
                 }
             else:
                 result = {"success": True, "question": None}
             return jsonify(result)
         abort(404)
     abort(422)
Exemple #9
0
    def create_question():
        body = request.get_json()
        #todo7
        if 'search_term' in body.keys():
            questions = Question.query.filter(
                Question.question.ilike('%' + body['search_term'] +
                                        '%')).all()
            formatted_questions = [question.format() for question in questions]

            return jsonify({
                "questions": formatted_questions,
                "total_questions": len(formatted_questions),
            })
        #todo5
        try:
            question = Question(
                question=body['question'],
                answer=body['answer'],
                difficulty=body['difficulty'],
                category=body['category'],
            )

            question.insert()
        except:
            return abort(400)

        return jsonify({
            "success": True,
            "created": question.format(),
        })
Exemple #10
0
    def create_question():
        # get body data as json
        body = request.get_json()

        if body is None:
            abort(422)

        question = (body.get("question"), )
        answer = (body.get("answer"), )
        category = (body.get("category"), )
        difficulty = body.get("difficulty")

        if not all([question, answer, category, difficulty]):
            abort(422)

        new_question = Question(
            question=question,
            answer=answer,
            category=category,
            difficulty=difficulty,
        )

        # insert
        new_question.insert()

        # response
        res = make_response(jsonify(new_question.format()), 201)

        return res
Exemple #11
0
 def get_question_for_quiz():
     if request.data:
         search_data = request.get_data('search_term')
         if ((b'quiz_category' in search_data
              and 'id' in search_data['quiz_category'])
                 and b'previous_questions' in search_data):
             questions_query = Question.query \
                             .filter_by(category=search_data['quiz_category']['id']) \
                             .filter(Question
                                     .id.notin_(search_data["previous_questions"]))\
                             .all()
             length_of_available_question = len(questions_query)
             if length_of_available_question > 0:
                 result = {
                     "success":
                     True,
                     "question":
                     Question.format(questions_query[random.randrange(
                         0, length_of_available_question)])
                 }
             else:
                 result = {"success": True, "question": None}
             return jsonify(result)
         abort(404)
     abort(422)
Exemple #12
0
 def add_question():
     """
     Used to create a new question
     """
     try:
         # Gets all the fields required for making Question
         request_json = request.get_json()
         question = request_json['question']
         answer_text = request_json['answer']
         category = request_json['category']
         difficulty = int(request_json['difficulty'])
         question = Question(question=question,
                             answer=answer_text,
                             category=category,
                             difficulty=difficulty)
         # adding the question created into the database
         db.session.add(question)
         db.session.commit()
         questions_query = Question.query.all()
         result = {
             "success": True,
             "question": question.format(),
             "total_questions": len(questions_query),
             "current_category": category
         }
         return jsonify(result)
     except Exception:
         # if there is a error
         db.session.rollback()
         abort(422)
     finally:
         db.session.close()
     return None
Exemple #13
0
    def test_create_new_question_success(self):
        """ Test create a question obj success """
        ## get the number of questions before creating a new question obj
        questions_total_before = len(Question.query.all())

        ## create a question obj
        question_test = Question(question='question',
                                 answer='answer',
                                 category='category',
                                 difficulty=1)

        ## load response data
        response = self.client().post('/questions',
                                      json=question_test.format())

        ## get the number of questions after creating a new question obj
        questions_total_after = len(Question.query.all())

        ## check success value, status_code
        self.assertTrue(json.loads(response.data)['success'])
        self.assertEqual(response.status_code, 200)

        ## compare the questions_total_before and questions_total_after to check if the obj deleted or not
        self.assertFalse(questions_total_before == questions_total_after)
        self.assertTrue(questions_total_before < questions_total_after)
Exemple #14
0
 def search_and_add_questions():
     """
     end point for search and add new question
     """
     searchTerm = request.json.get("searchTerm", None)
     if searchTerm:
         questions = Question.query.filter(
             Question.question.ilike("%{}%".format(searchTerm)))
         return jsonify({
             "questions":
             list(map(lambda question: question.format(), questions)),
             "total_questions":
             len(questions.all()),
             "categories": {
                 category.id: category.type
                 for category in Category.query.all()
             },
             "current_category":
             "",
             "success":
             True
         }), 200
     else:
         question = Question(**request.json)
         question.insert()
         return jsonify({
             "question": question.format(),
             "success": True
         }), 200
  def play_quiz():
      
    data = request.get_json()
    previous_questions = data.get('previous_questions')
    quiz_category = data.get('quiz_category')

    if ((quiz_category is None) or (previous_questions is None)):
      abort(400)
      
    if ( quiz_category['id'] == 0):
      questions_query = Question.query.filter(Question.id.notin_(previous_questions)).all()
    else:
      questions_query = Question.query.filter_by(category=quiz_category['id']).filter(Question.id.notin_(previous_questions)).all()

    length_of_questions = len(questions_query)
    if length_of_questions > 0 :
      result = {
        "success": True,
        "question": Question.format(questions_query[random.randint(0, length_of_questions-1 ) ] )
      }
    else:
      result = {
        "success": True,
        "question": None
      }  
    return jsonify(result)  
    def create_questions():
        try:
            body = request.get_json(force=True)
            if not ('question' in body and 'answer' in body
                    and 'category' in body and 'difficulty' in body):
                abort(422)
            new_question = body.get('question')
            new_answer = body.get('answer')
            new_category = body.get('category')
            difficulty = body.get('difficulty')
            question = Question(question=new_question,
                                answer=new_answer,
                                category=new_category,
                                difficulty=difficulty)
            question.insert()

            questions = Question.query.order_by(Question.id).all()

            return jsonify({
                'success':
                True,
                'questions': [question.format() for question in questions],
                'totalQuestions': (len(questions)),
                'currentCategory':
                None
            })
        except:
            abort(422)
Exemple #17
0
  def create_question():
    body = request.get_json()
    searchTerm = body.get('searchTerm', None)
    question = body.get('question', None)
    answer = body.get('answer', None)
    difficulty = body.get('difficulty', None)
    category = body.get('category', None)

    try:
      if searchTerm:
        questions = Question.query.filter(Question.question.ilike(f'%{searchTerm}%')).all()
        current_questions = paginate_questions(request, questions)

        return jsonify({
          'success': True,
          'questions': current_questions,
          'total_questions': len(current_questions)
        })

      else:
        newQuestion = Question(question, answer, difficulty, category)
        newQuestion.insert()

        return jsonify({
          'success': True,
          'question_created': newQuestion.format()
        })
    except Exception as error:
      print("\nerror => {}\n".format(error))
      abort(422)
Exemple #18
0
 def crate_questions():
     body = request.get_json()
     new_question = body.get('question')
     new_answer = body.get('answer')
     new_category = body.get('category')
     new_difficulty = body.get('difficulty')
     if (new_question or new_answer or new_category
             or new_difficulty) is None:
         abort(404)
     try:
         question = Question(question=new_question,
                             answer=new_answer,
                             category=new_category,
                             difficulty=new_difficulty)
         question.insert()
         total_questions = len(Question.query.all())
         current_questions = question.format()
         return jsonify({
             'success': True,
             'created': question.id,
             'current_questions': current_questions,
             'total_questions': total_questions
         })
     except:
         abort(422)
Exemple #19
0
    def get_quizzes():
        body = request.get_json()
        previous_questions = body.get('previous_questions', [])
        quiz_category = body.get('quiz_category', None)
        category_id = int(quiz_category['id'])
        try:
            if category_id == 0:
                questions = Question.query.filter(
                    Question.id.notin_(previous_questions)).all()
            else:
                questions = Question.query.filter(
                    Question.category == quiz_category['id']).filter(
                        Question.id.notin_(previous_questions)).all()
            available_questions = len(questions)

            if available_questions > 0:
                return jsonify({
                    'success':
                    True,
                    'question':
                    Question.format(questions[random.randrange(
                        0, available_questions)]),
                    'category_id':
                    category_id
                })
            else:
                return jsonify({'success': False, 'question': None})
        except:
            abort(422)
Exemple #20
0
    def create_question():
        res_json = request.get_json()
        list_json = list(res_json.keys())
        list_json.sort()
        if list_json != [
                "answer",
                "category",
                "difficulty",
                "question",
        ]:
            abort(400)
        question = res_json["question"]
        answer = res_json["answer"]
        category = res_json["category"]
        difficulty = res_json["difficulty"]

        try:
            new_question = Question(
                question=question,
                answer=answer,
                category=category,
                difficulty=difficulty,
            )
            new_question.insert()
            return (
                jsonify({
                    "success": True,
                    "question": new_question.format()
                }),
                200,
            )
        except Exception:
            abort(500)
Exemple #21
0
    def add_question():
        try:
            data = request.get_json()
        except Exception:
            abort(400, 'Invalid data')

        question = data.get('question')
        answer = data.get('answer')
        difficulty = data.get('difficulty')
        category = data.get('category')

        if not question or not answer or not difficulty or not category:
            abort(400, 'Invalid question data.')

        category = Category.query.filter(Category.id == category).one_or_none()
        if category is None:
            abort(400, 'Specified category not found.')

        try:
            question = Question(question, answer, category.id, difficulty)
            question.category = category
            question.insert()

            return jsonify(question.format())
        except Exception:
            abort(500, "Failed to save question")
            pass
Exemple #22
0
    def create_question():
        #Get the request body
        body = request.get_json()

        #Get the values for question, answer, category and difficulty
        new_question = body.get('question', None)
        new_answer = body.get('answer', None)
        new_category = body.get('category', None)
        new_difficulty = body.get('difficulty', None)

        # Try to insert the values that were taken from the request body
        try:
            question = Question(question=new_question,
                                answer=new_answer,
                                category=new_category,
                                difficulty=new_difficulty)
            question.insert()

            selection = Question.query.order_by(Question.id).all()
            #Paginate the selection with the iserted questions
            current_questions = paginate_questions(request, selection)

            return jsonify({
                'success': True,
                'created': question.id,
                'created_question': question.format(),
                #'questions': current_questions,
                'total_questions': len(Question.query.all())
            })

        except:
            abort(422)
Exemple #23
0
    def create_question():
        if request.method != 'POST': abort(405)
        body = request.get_json()

        new_question = body.get('question', None)
        new_answer = body.get('answer', None)
        new_category = body.get('category', None)
        new_difficulty = body.get('difficulty', None)

        try:
            question = Question(question=new_question,
                                answer=new_answer,
                                category=new_category,
                                difficulty=new_difficulty)
            # print(f'{Fore.GREEN} question ', question.category, type(question.difficulty), question.answer, question.question)
            # print(f'{Fore.WHITE}')
            question.insert()

            questions = Question.query.order_by(Question.id).all()
            current_questions = [question.format() for question in questions]
            lastIndex = len(current_questions) - 1
            return jsonify({
                'success': True,
                'created': question.id,
                'question': current_questions[lastIndex],
                'total_questions': len(Question.query.all())
            })
        except:
            abort(422)
Exemple #24
0
    def create_question():
        body = request.get_json()
        question = body.get('question', None)
        answer = body.get('answer', None)
        category = body.get('category', None)
        difficulty = body.get('difficulty', None)
        if (question == '') or (answer == '') or (category
                                                  == '') or (difficulty == ''):
            abort(400)

        try:
            item = Question(question=question,
                            answer=answer,
                            category=category,
                            difficulty=difficulty)
            item.insert()

            return jsonify({
                'success': True,
                'created': item.id,
                'question_info': item.format(),
                'total_questions': len(Question.query.all())
            })
        except:
            abort(500)
Exemple #25
0
    def create_or_search_question():
        body = request.get_json()

        if not body:
            abort(400)

        question = body.get('question', None)
        answer = body.get('answer', None)
        category = body.get('category', None)
        difficulty = body.get('difficulty', None)
        search_term = body.get('searchTerm', None)

        # if not questions search case, any missing args in the body will be considered bad request
        if search_term is None:
            for arg in ['question', 'answer', 'category', 'difficulty']:
                if arg not in body:
                    abort(400)

        try:
            if search_term is not None:
                questions = Question.query.filter(
                    Question.question.ilike('%{}%'.format(search_term))).all()
                selection = [question.format() for question in questions]
                current_questions = paginate_questions(request, selection)
                return jsonify({
                    'success': True,
                    'questions': current_questions,
                    'total_questions': len(selection),
                    'current_category': None
                })

            else:
                for arg in [question, answer, category, difficulty]:
                    if not arg:
                        abort(422)
                if not Category.query.get(category):
                    abort(422)
                question = Question(question=question,
                                    answer=answer,
                                    category=category,
                                    difficulty=difficulty)
                question.insert()
                question_id = question.id
                selection = [
                    question.format() for question in Question.query.all()
                ]
                current_questions = paginate_questions(request, selection)
                return jsonify({
                    'success': True,
                    'created': question_id,
                    'questions': current_questions,
                    'total_questions': len(selection),
                    'current_category': None
                })
        except:
            rollback()
            print(sys.exc_info())
            abort(422)
        finally:
            close_connection()
Exemple #26
0
 def post_question():
     success = False
     try:
         question = request.json.get('question', None)
         answer = request.json.get('answer', None)
         difficulty = request.json.get('difficulty', None)
         category = request.json.get('category', None)
         if not (question and answer and category and difficulty):
             return abort(
                 400, 'Required question details are missing. Please retry',
                 'body')
         question_instance = Question(question, answer, category,
                                      difficulty)
         question_instance.insert()
         success = True
         question_list = Question.query.all()
         paginated_question_list = paginate_questions(
             request, question_list)
         return jsonify({
             'success': True,
             'questions': paginated_question_list,
             'total_questions': len(question_list),
             'question_added': question_instance.format()
         })
     except BaseException:
         return abort(422, 'An Error occurred, please retry', 'body')
Exemple #27
0
    def create_question():
        body = request.get_json()

        new_question = body.get('question')
        new_answer = body.get('answer')
        new_difficulty = body.get('difficulty')
        new_category = body.get('category')

        try:
            question = Question(question=new_question,
                                answer=new_answer,
                                difficulty=new_difficulty,
                                category=new_category)
            question.insert()

            selection = Question.query.order_by(Question.id).all()
            # current_questions = paginate_books(request, selection)
            return jsonify({
                'success': True,
                'question': question.format(),
                'created': question.id,
                'total_questions': len(selection)
            })
        except ValueError:
            abort(422)
Exemple #28
0
    def create_question():
        try:
            # get the question attributes
            body = request.get_json()
            new_question = body.get("question", None)
            new_answer = body.get("answer", None)
            new_category = body.get("category", None)
            new_difficulty = body.get("difficulty", None)
    
            if not new_question or not new_answer or not new_category or not new_difficulty:
                abort(422)
            #  create new question and add it
            question = Question(
              new_question, new_answer, new_category, new_difficulty)
            
            question.insert()
            questions = Question.query.all()
            # get category type
            category = db.session.query(Category.type).\
                         filter(new_category == Category.id).all()
            # make the json response
            return jsonify({
                    'success': True,
                    'questions': question.format(),
                    'total_questions': len(questions),
                    'current_category': category})

        except:
            # if the proccess uncompleted because of any issue wil abort 422
            abort(422)
Exemple #29
0
  def create_question():
      body = request.get_json()

      new_question = body.get('question', None)
      new_difficulty = body.get('difficulty', None)
      new_category = body.get('category', None)
      new_answer = body.get('answer', None)
      searchTerm = body.get('searchTerm', None)

      try:
         if searchTerm:
           selection = Question.query.order_by(Question.id).filter(Question.question.ilike('%{}%'.format(searchTerm)))
           current_questions = paginate_questions(request, selection)


           return jsonify({
              'success': True,
              'questions': current_questions,
              'total_questions': len(selection.all()),
              'current_category': None
            })
         else:
           category = Category.query.filter_by(id=new_category).one_or_none()
           question = Question(question=new_question, answer=new_answer,difficulty=new_difficulty, category=category.type)
           question.insert()

           return jsonify({
             "success": True,
             "question": question.format()
            })

      except():
          abort(422)
Exemple #30
0
 def paginate_question(request, selection):
   page = request.args.get('page', 1, type=int)
   start =  (page - 1) * QUESTIONS_PER_PAGE
   end = start + QUESTIONS_PER_PAGE
   question = [Question.format(question1) for question1 in selection]
   current_question = question[start:end]
   return current_question