Esempio n. 1
0
    def test_successful_question_delete(self):
        # insert mock qestion into Question constructor
        question = Question(
            question='This is a test question that should deleted',
            answer='this answer should be deleted',
            difficulty=1,
            category='1')

        # create a new mock question in the database
        question.insert()        
        # create mock question and get id
        mock_question_id = question.id

        # delete mock question and process response
        response = self.client().delete(
            '/questions/{}'.format(mock_question_id))
        data = json.loads(response.data)

        # ensure question does not exist
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['message'], "Question successfully deleted")
Esempio n. 2
0
  def create_question():
    body = request.get_json()

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

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

        if(len(current_questions)==0):
          abort(404)
        else:
          return jsonify({
            'questions': current_questions,
            'total_questions': len(Question.query.all()),
            'current_category': [(question['category']) for question in current_questions]
            })
      else:
        question_new = Question(question=new_question, answer=new_answer, category=new_category, difficulty=new_difficulty)
        question_new.insert()

        selection=Question.query.order_by(Question.id).all()
        current_questions = paginate(request,selection)

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

    except:
      abort(422)
Esempio n. 3
0
    def get(self):
        result = urlfetch.fetch("https://opentdb.com/api.php?amount=10&encode=url3986").content
        json_result = json.loads(result)["results"]

        for q in json_result:
            question = q["question"]
            final_question = urlparse.unquote(question)

            correct_answer = q["correct_answer"]
            final_correct_answer = urlparse.unquote(correct_answer)

            incorrect_answers = q["incorrect_answers"]
            final_incorrect_answers = []
            for answer in incorrect_answers:
                final_incorrect_answers.append(urlparse.unquote(answer))

            new_question = Question(question = final_question,
            correct_answer = final_correct_answer,
            incorrect_answers = final_incorrect_answers)

            new_question.put()
        self.redirect("/")
Esempio n. 4
0
 def add_question():
     try:
         req_body = request.get_json()
         new_question = req_body.get('question', None)
         new_answer = req_body.get('answer', None)
         new_difficulty = req_body.get('difficulty', None)
         new_category = req_body.get('category', None)
         question = Question(question=new_question,
                             answer=new_answer,
                             difficulty=new_difficulty,
                             category=new_category)
         question.insert()
         result = pagination(request, QUESTIONS_PER_PAGE)
         result = result.get_json()
         return jsonify({
             "success": True,
             "created_id": question.id,
             "questions": result["questions"],
             "totalQuestions": result["totalQuestions"]
         })
     except:
         abort(422)
Esempio n. 5
0
 def add_question():
     body = request.get_json()
     try:
         question_text = body["question"]
         answer = body["answer"]
         category = body["category"]
         difficulty = body["difficulty"]
         new_question = Question(question=question_text,
                                 answer=answer,
                                 category=str(category),
                                 difficulty=difficulty)
         new_question.insert()
         updated_questions = Question.query.order_by(Question.id).all()
         paginated_list = paginate(updated_questions)
         return jsonify({
             "success": True,
             "created": new_question.id,
             "questions": paginated_list,
             "total_questions": len(updated_questions)
         })
     except:
         abort(400)
Esempio n. 6
0
 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=new_difficulty)
         question.insert()
         selection = Question.query.order_by(Question.id).all()
         current_questions = paginate_questions(request, selection)
         return jsonify({
             'success': True,
             'created': question.id,
             'questions': current_questions,
             'total_questions': len(Question.query.all())
         })
     except:
         abort(422)
Esempio n. 7
0
    def create_a_question():
        # get the data from request
        body = request.get_json()

        try:
            # check if there is None value in the input
            if None in [
                    body.get('question'),
                    body.get('answer'),
                    body.get('category'),
                    body.get('difficulty')
            ]:
                abort(422)

            # create a Question object
            new_question = Question(question=body.get('question'),
                                    answer=body.get('answer'),
                                    category=body.get('category'),
                                    difficulty=body.get('difficulty'))

            # insert to database
            new_question.insert()

            # get all questions and paginate
            questions = Question.query.order_by(Question.id).all()
            current_questions = paginate_questions(request, questions)

            # return data to view
            return jsonify({
                'success': True,
                'created': new_question.id,
                'question_created': new_question.question,
                'questions': current_questions,
                'total_questions': len(Question.query.all())
            }), 200

        except:
            # if error happens, abort
            abort(422)
Esempio n. 8
0
    def create_trivia_question():
      def format_paginated_questions(selection):
        question_dict={}
        for key, value in vars(selection).items():
          print("key", key)
          question_dict[key] =  value
        return question_dict
      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 == None) or (answer == None) or (difficulty == None) or (category == None)):
        abort(422)
        
        
      try:
        new_question = Question(question=question, answer=answer, category=category, difficulty=difficulty)
        new_question.insert()
      
        questions_all = Question.query.order_by(Question.id).all()
        question_num = len(questions_all)
        page = math.ceil(question_num/QUESTIONS_PER_PAGE)
        questions_dict = Question.query.order_by(Question.id).paginate(page, per_page=QUESTIONS_PER_PAGE, error_out=False)
 

        current_questions = format_paginated_questions(questions_dict)
        questions = [question.format() for question in current_questions["items"]]
        
        return jsonify({
        "success": True,
        "page": current_questions["page"],
        "questions": questions,
        "total_questions": current_questions["total"],
        })
      
      except:
        abort(422)
Esempio n. 9
0
    def add_question():

        question_form = request.get_json()
        # category id is incremented by 1 because on the front end category is an array of string and its index/id starts at 0
        category_id = int(question_form.get('category')) + 1
        try:
            new_question = Question(question=question_form.get('question'), answer=question_form.get('answer'),
                                    difficulty=question_form.get('difficulty'), category_id=category_id)

            new_question.insert()
            id = new_question.id

        except:
            abort(422)
            print(sys.exc_info())

        finally:
            db.session.close()

        # i'm returning id for testing purposes
        return {"success": True,
                "id": new_question.id}
Esempio n. 10
0
    def create_question():
        '''
      Will create or search for questions
      If search is used questions will be paginated using def paginate_questions
      '''
        body = request.get_json()

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

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

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

        if not question or not answer or not category or not difficulty:
            abort(400)

        try:
            question = Question(question=question,
                                answer=answer,
                                difficulty=difficulty,
                                category=category)

            question.insert()

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

        except:
            abort(422)
    def test_get_category_questions(self):
        new_category = self.new_category.copy()
        new_question = self.new_question.copy()
        category = Category(type=new_category['type'])
        category.insert()
        question = Question(question=new_question['question'],
                            answer=new_question['answer'],
                            difficulty=new_question['difficulty'],
                            category=str(category.id))
        question.insert()

        category_questions = Question.query.filter_by(
            category=str(category.id)).all()
        res = self.client().get('/api/v1/categories/{}/questions'.format(
            category.id))
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(isinstance(data['questions'], collections.Iterable),
                         True)
        self.assertEqual(data['total_questions'], len(category_questions))
Esempio n. 12
0
    def create_question():
        data = request.get_json()
        print(data.get('question'))

        question = data.get('question', None)
        answer = data.get('answer', None)
        category = data.get('category', None)
        difficulty = data.get('difficulty', None)
        # Check if all required info is in request body
        if question and answer and category and difficulty:
            try:
                question = Question(question=question,
                                    answer=answer,
                                    category=category,
                                    difficulty=difficulty)

                question.insert()
                return jsonify({'success': True, 'created': question.id})
            except exc.SQLAlchemyError:
                abort(422)
        else:
            abort(400)
Esempio n. 13
0
  def add_question():
    try:
      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)

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

      return jsonify({
        'success': True,
        'created': question.id,
      })

    except:
      abort(422)
Esempio n. 14
0
    def test_delete_question(self):
        question = Question(
            question=self.delete_new_question['question'],
            answer=self.delete_new_question['answer'],
            category=self.delete_new_question['category'],
            difficulty=self.delete_new_question['difficulty'],
        )
        question.insert()
        question.update()

        get_new_question = Question.query.filter(
            Question.question == self.delete_new_question['question']).all()
        id_new = str(get_new_question[0].id)

        res = self.client().delete('/questions/' + id_new)
        data = json.loads(res.data)

        did_delete = Question.query.filter(Question.id == id_new).one_or_none()
        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['deleted'], id_new)
        self.assertEqual(did_delete, None)
Esempio n. 15
0
    def new_questions():

        data = request.get_json()
        question = data.get('question', '')
        answer = data.get('answer', '')
        difficulty = data.get('difficulty', '')
        category = data.get('category', '')

        try:
            if (question == '') or (answer == '') or (difficulty == ''):
                abort(400)

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

            return jsonify({"success": True})

        except:
            abort(400)
Esempio n. 16
0
    def add_question():
        body = request.get_json()
        category_id = body.get('category')
        question_text = body.get('question')
        question_answer = body.get('answer')
        category = Category.query.get(category_id)
        if category is None or len(question_text) == 0 or len(
                question_answer) == 0:
            abort(422)

        question = Question(question=question_text,
                            category=category_id,
                            answer=question_answer,
                            difficulty=body.get('difficulty'))
        question.insert()

        result = {
            'success': 1,
            'message': 'Question has been added',
            'id': question.id
        }
        return jsonify(result)
Esempio n. 17
0
    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)

        if not new_question:
            abort(400, {'message': 'Question can not be blank'})
        elif not new_answer:
            abort(400, {'message': 'Answer can not be blank'})
        else:
            try:
                question = Question(question=new_question,
                                    answer=new_answer,
                                    category=new_category,
                                    difficulty=new_difficulty)

                question.insert()
                session_commit()

                selection = Question.query.order_by(Question.id).all()
                current_questions = paginate_questions(request, selection)

                return jsonify({
                    'success': True,
                    'created': question.id,
                    'questions': current_questions,
                    'total_questions': len(selection)
                })

            except:
                flash(
                    'An error occurred due to database insertion error. Question could not be listed.'
                )
                # session_rollback()
                abort(400)
            finally:
                session_close()
Esempio n. 18
0
    def test_delete_question(self):
        question = Question(question="Q", answer='A', category=1, difficulty=1)
        question.insert()
        question_id = question.id
        print('question: ', question, ' question id: ', question_id)

        questions_before_delete = Question.query.all()

        response = self.client().delete('/questions/{}'.format(question_id))
        data = json.loads(response.data)
        print('response: ', response, ' data :', data)

        questions_after_delete = Question.query.all()
        question = Question.query.filter(
            Question.id == question_id).one_or_none()

        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['deleted'], question_id)
        self.assertTrue(
            len(questions_before_delete) - len(questions_after_delete) == 1)
        self.assertEqual(question, None)
Esempio n. 19
0
    def create_question():
        try:
            body = request.get_json()

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

            question = Question(question=new_question,
                                answer=new_answer,
                                category=new_category,
                                difficulty=new_difficulty)

            question.insert()
            return jsonify({'success': True})
        except:
            abort(422)
    def createQuestion():
        body = request.get_json()
        try:
            search = body.get('search', None)
            if search:
                selection = Question.query.filter(
                    Question.question.ilike("%{}%".format(search))).all()
                if len(selection) == 0:
                    abort(404)
                currentQuestions = paginate_books(request, selection)
                return jsonify({
                    'success': True,
                    'questions': currentQuestions,
                    'total_questions': len(Question.query.all())
                })
            else:
                questionText = body.get('question')
                answerText = body.get('answer')
                categoryText = body.get('category')
                difficultyNo = int(body.get('difficulty'))
                if (questionText is None) or (categoryText is None) or (
                        answerText is None) or (difficultyNo is None):
                    abort(400)

                question = Question(question=questionText,
                                    answer=answerText,
                                    category=categoryText,
                                    difficulty=difficultyNo)
                question.insert()
                selection = Question.query.order_by(Question.id).all()
                currentQuestions = paginate_books(request, selection)

                return jsonify({
                    'success': True,
                    'questions': currentQuestions,
                    'total_questions': len(selection)
                })
        except:
            abort(422)
Esempio n. 21
0
 def add_question():
     # curl -X POST http://127.0.0.1:5000/add
     data = request.get_json()
     try:
         new_question = Question(question=data['question'],
                                 answer=data['answer'],
                                 difficulty=data['difficulty'],
                                 category=data['category'])
         new_question.insert()
         questions = Question.query.all()
         total_questions = len(questions)
         current_questions = paginate_questions(
             request,
             questions)  #note, request has not changed when we press delete
         return jsonify({
             'success': True,
             'total_questions': total_questions,
             'questions': current_questions,
             'created': new_question.id
         })
     except:
         abort(422)
Esempio n. 22
0
    def create_questions():
        body = request.get_json()
        new_question = body.get('question')
        new_answer = body.get('answer')
        new_difficulty = body.get('difficulty')
        new_category = body.get('category')

        if new_question is None or new_answer is None or new_difficulty is None or new_category is None:
            abort(400)

        try:
            new_data = Question(
                new_question,
                new_answer,
                new_category,
                new_difficulty)
            new_data.insert()
            return jsonify({
                'success': True
            })
        except BaseException:
            abort(422)
Esempio n. 23
0
    def add_question():
        # handle add questions and search questions by title
        body = request.get_json()
        if 'question' in body and 'answer' in body and 'difficulty' in body and 'category' in body:
            try:
                question = body.get('question')
                answer = body.get('answer')
                difficulty = body.get('difficulty')
                category_id = body.get('category')

                new_question = Question(question=question,
                                        answer=answer,
                                        difficulty=difficulty,
                                        category=category_id)
                new_question.insert()
                response = {'success': True, 'created': new_question.id}
            except:
                abort(422)
        elif 'searchTerm' in body:
            try:
                title = body.get('searchTerm')
                if title is None or title == '':
                    abort(422)
                questions = Question.query.filter(
                    Question.question.ilike('%{}%'.format(title))).all()
                formatted_questions = [
                    question.format() for question in questions
                ]
                response = {
                    'success': True,
                    'questions': formatted_questions,
                    'total_questions': len(formatted_questions),
                    'current_category': None
                }
            except:
                abort(422)
        else:
            abort(400)
        return jsonify(response)
Esempio n. 24
0
    def post_question():
        # if the request sent was a search request
        if ('searchTerm' in json.loads(request.data)):
            search_term = json.loads(request.data)['searchTerm']
            questions = Question.query.filter(
                Question.question.ilike('%' + search_term + '%')).all()
        # if not, it was a request to add a new question
        else:
            question_data = json.loads(request.data)

            # If the question or answer sent are empty, returns an error.
            # Otherwise creates a new Question object.
            if (question_data['question'] == ''
                    or question_data['answer'] == ''):
                abort(422)
            else:
                question = Question(question=question_data['question'],
                                    answer=question_data['answer'],
                                    difficulty=question_data['difficulty'],
                                    category=question_data['category'])

            # Try to add the new question to the database
            try:
                question.insert()
                questions = Question.query.all()
            except Exception as e:
                abort(422)

        # Gets paginated questions for display. If there was a search, the
        # questions are the ones matching the search filter. If the user added
        # a question, it simply returns all questions.
        current_page = request.args.get('page', 1, type=int)
        paginated_questions_list = paginate_questions(questions, current_page)

        return jsonify({
            'success': True,
            'questions': paginated_questions_list,
            'total_questions': len(questions)
        })
Esempio n. 25
0
    def create_question():
        """This endpoint creates a question.

        A 422 status code is returned if the any of
        the json data is empty.
        """
        # Get json data from request
        data = request.get_json()

        # get individual data from json data
        question = data.get('question', '')
        answer = data.get('answer', '')
        difficulty = data.get('difficulty', '')
        category = data.get('category', '')

        # validate to ensure no data is empty
        if ((question == '') or (answer == '') or (difficulty == '')
                or (category == '')):
            abort(422)

        try:
            # Create a new question instance
            question = Question(question=question,
                                answer=answer,
                                difficulty=difficulty,
                                category=category)

            # save question
            question.insert()

            # return success message
            return jsonify({
                'success': True,
                'message': 'Question successfully created!'
            }), 201

        except Exception:
            # return 422 status code if error
            abort(422)
Esempio n. 26
0
 def post_question():
     try:
         data = request.get_json()
         question_text = data.get('question', '')
         answer_text = data.get('answer', '')
         category = data.get('category', 1)
         difficulty = data.get('difficulty', 1)
         question = Question(question=question_text,
                             answer=answer_text,
                             category=category,
                             difficulty=difficulty)
         question.insert()
         questions = Question.query.all()
         formatted_questions = pagenate_questions(request, questions)
         return jsonify({
             'created': question.id,
             'questions': formatted_questions,
             'total_questions': len(questions),
             'success': True
         })
     except BaseException:
         abort(422)
Esempio n. 27
0
 def create_New_question():
     Message_body = request.get_json()
     search = Message_body.get('searchTerm', None)
     if search is not None:
         result = Question.query.filter(
             Question.question.ilike(f'%{search}%'))
         current_questions = [q.format() for q in result]
         if len(current_questions) == 0:
             abort(404)
         else:
             return jsonify({
                 'success':
                 True,
                 'search_term':
                 search,
                 'questions':
                 current_questions,
                 'total_matching_questions':
                 len(current_questions),
                 'total_questions':
                 len(Question.query.all())
             })
     else:
         Newquestion = Message_body.get('question', None)
         NewAnswer = Message_body.get('answer', None)
         NewCategory = Message_body.get('category', None)
         NewDifficulty = Message_body.get('difficulty', None)
         if ((Newquestion is None) or (NewAnswer is None)
                 or (NewDifficulty is None) or (NewCategory is None)):
             abort(422)
         try:
             question = Question(question=Newquestion,
                                 answer=NewAnswer,
                                 category=NewCategory,
                                 difficulty=NewDifficulty)
             question.insert()
             return jsonify({'success': True})
         except:
             abort(400)
Esempio n. 28
0
    def add_question():
        data = request.get_json()
        new_question = data['question']
        new_answer = data['answer']
        new_difficulty = data['difficulty']
        new_category = data['category']

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

                return jsonify({'success': True})
            except:
                abort(422)
        else:
            abort(400)
Esempio n. 29
0
 def create_question():
     body = request.get_json()
     if body.get('searchTerm'):
         search = body.get('searchTerm')
         selection = \
             Question.query.order_by(Question.id).filter(Question.question.ilike('%{}%'.format(search))).all()
         if len(selection) == 0:
             abort(404)
         paginated = paginate_questions(request, selection)
         return jsonify({
             'success': True,
             'questions': paginated,
             'total_questions': len(Question.query.all())
         })
     else:
         new_question = body.get('question')
         new_answer = body.get('answer')
         new_difficulty = body.get('difficulty')
         new_category = body.get('category')
         if new_question is None or new_answer is None \
             or new_difficulty is None or new_category is None:
             abort(422)
         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_questions(request, selection)
             return jsonify({
                 'success': True,
                 'created': question.id,
                 'created_question': question.question,
                 'questions': current_questions,
                 'total_questions': len(Question.query.all()),
             })
         except:
             abort(422)
Esempio n. 30
0
    def add_question():
        form_data = request.json
        if "searchTerm" in form_data:
            search_term = form_data["searchTerm"].strip()
            questions = Question.query.filter(
                Question.question.ilike(f"%{search_term}%")).all()
            current_questions = [q.format() for q in questions]
            return jsonify({"success": True, "questions": current_questions})
        else:
            if (form_data['question'].strip()
                    == "") or (form_data["answer"].strip() == ""):
                abort(400)
            try:
                new_question = Question(question=form_data['question'].strip(),
                                        answer=form_data['answer'].strip(),
                                        category=form_data['category'],
                                        difficulty=form_data['difficulty'])
                new_question.insert()
            except Exception:
                abort(422)

            return jsonify({"success": True, "added": new_question.id})