Beispiel #1
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
Beispiel #2
0
  def search_questions():
     # this is an endpoint to handle both adding a new question and searching for questions
     # for adding a new question, the searchterm is added to the URL with a value of null, 
     # indiciating that we use the endpoint for adding a question. If no searchterm is in the 
     # URL, then we know that we are searching for the questions by phrase.

     body = request.get_json()
     
     if body is None:
        abort(400)
     else:
        searchterm = request.args.get('searchTerm', '', type=str)
        if searchterm == 'null':
           # Add question

           question = body.get('question')
           answer = body.get('answer')
           difficulty = body.get('difficulty')
           category = body.get('category')
   
           if not question or not answer or not difficulty or not category:
           #if question == '' or answer == '':
              # Error, we must have question, answer, difficulty and category in the request body.

              abort(400)
           else:
              #print(f'Q:{question} A:{answer} D:{difficulty} C:{category}')
              q = Question(question, answer, int(category), difficulty)
              try:
                 q.insert()
              except:
                 abort(422)
              return jsonify({'success': True})
        else:
           searchterm = body.get('searchTerm')
           if searchterm:
              # we search the questions by pharse.

              questions = Question.query.filter(Question.question.ilike(f'%{searchterm}%')).all()
              #questions = Question.query.filter(Question.question.ilike('%Q%')).all()
              formatted_questions = []

              if questions:
                 for q in questions:
                    q.category = int(q.category)
                    #q.category -= 1
                    formatted_questions.append(q.format())

                 return jsonify({
			'questions': formatted_questions[:QUESTIONS_PER_PAGE],
			'total_questions': len(formatted_questions),
			'current_category': 0,
			'searchTerm': searchterm,
			'success': True
			})
              else:
                 abort(404)
           else:
              abort(400)
Beispiel #3
0
 def addQuestion():
     try:
         question = Question(question=request.json['question'],answer=request.json['answer'] \
           , difficulty=request.json['difficulty'], category=request.json['category'])
         question.category = int(question.category)
         question.insert()
         return jsonify({"success": "True"})
     except:
         abort(422)
Beispiel #4
0
 def insert_questions_for_test(self, category, count=15):
     questions = []
     for i in range(count):
         question = Question('Q%s' % i, 'A%s' %
                             i, category.id, randint(1, 4))
         question.category = category
         question.insert()
         questions.append(question)
     return questions
Beispiel #5
0
 def test_get_questions_one_record(self):
     category = Category("Science")
     category.insert()
     question = Question('Q1', 'A1', "1", category.id)
     question.category = category
     question.insert()
     response = self.client().get('/api/questions')
     data = response.get_json()
     print(data)
     # self.assertEqual(data['questions'], [])
     self.assertEqual(data['total_questions'], 1)
     self.assertEqual(response.status_code, 200)
     question.delete()
     category.delete()
Beispiel #6
0
def insert_dummy_data():
    """Utility function to insert dummy data"""
    dummy_category = {'type': 'History'}
    dummy_question = {
        'question': 'A dummy question ?',
        'answer': 'Dummy answer',
        'difficulty': 1
    }
    sample_category = Category(**dummy_category)
    sample_question = Question(**dummy_question)
    sample_question.category = sample_category
    sample_question.insert()

    return sample_question.id
Beispiel #7
0
    def test_search_questions_non_matching_word(self):
        category = Category("Science")
        category.insert()
        question = Question('Who moved my cheese', 'Not Me!', "1", category.id)
        question.category = category
        question.insert()

        response = self.client().post('/api/questions/search',
                                      json={'searchTerm': 'happy'})
        data = response.get_json()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['total_questions'], 0)

        question.delete()
        category.delete()
Beispiel #8
0
    def test_get_random_question_for_last_question(self):
        category = Category("Science")
        category.insert()
        question = Question('Who moved my cheese', 'Not Me!', "1", category.id)
        question.category = category
        question.insert()

        response = self.client().post('/api/quizzes', json={
            'previous_questions': [question.id],
            'quiz_category': None
        })
        data = response.get_json()

        self.assertEqual(response.status_code, 200)
        self.assertEqual(data.get('question'), None)

        question.delete()
        category.delete()
Beispiel #9
0
    def test_delete_question_invalid_id(self):
        category = Category("Science")
        category.insert()
        question = Question('Who moved my cheese', 'Not Me!', "1", category.id)
        question.category = category
        question.insert()

        response = self.client().delete('/api/questions/1')
        data = response.get_json()

        self.assertEqual(response.status_code, 200)
        dbEntry = Question.query.filter(
            Question.id == question.id).one_or_none()
        self.assertNotEqual(dbEntry, None)
        self.assertEqual(dbEntry.question, question.question)

        question.delete()
        category.delete
Beispiel #10
0
    def create_question():
        data = request.get_json()
        expected_data_keys = sorted(
            ['question', 'answer', 'category', 'difficulty'])

        # Checking if all the columns(keys) exist in the incoming data
        if sorted([key for key in data]) == expected_data_keys:
            category = data.pop('category')
            new_question = Question(**data)

            try:
                new_question.category = Category.query.get(category)
                new_question.insert()
                return jsonify({
                    'success': True,
                    'new_question': new_question.format()
                }), 201
            except Exception:
                abort(500)
        else:
            abort(400)
Beispiel #11
0
  def add_question():
    try:
      # formData = Question(request.get_json().get('question'),request.get_json().get('answer'),request.get_json().get('category'),request.get_json().get('difficulty'))
      formData = Question('', '', 0, 0)
      formData.question = request.get_json().get('question')
      formData.category = request.get_json().get('category')
      formData.answer = request.get_json().get('answer')
      formData.difficulty = request.get_json().get('difficulty')
      #print(formData.question)

      if(formData.question and formData.answer and formData.category and formData.difficulty):
        Question.insert(formData)
        return jsonify({
          'success':True
        })  
      else:
         return jsonify({
          'success':False,
          'message':'Check All required Fields'

        })
    except Exception as e:
      print(e)
      abort(422)