示例#1
0
def asking(request, **kwargs):
    try:
        q_body = request.form['question-body']
        q_title = request.form['question-title']
        q_cat = request.form['question-category']
    except KeyError:
        return questions(request)

    q = Question()
    q.views = 0
    q.votes = 0
    q.body = q_body
    q.title = q_title
    q.category_id = Category.get(where=('category_name',q_cat))[0].id
    q.user_id = local.request.session['uid']

    q.insert()
    return question(request, qid = q.id)
示例#2
0
  def post_question():
    body = request.get_json()
    search = body.get('searchTerm')
    if(search):
      search = "%" + search +"%"
      searchResult =  Question.query.filter(Question.question.ilike(search)).all()
      if (len(searchResult) == 0):
        abort(404)
      else:
        pagedResult = pagination(request, searchResult)
        return  jsonify({
          'success' : True,
          'questions' : pagedResult,
          'total_questions': len(searchResult)
        })
    else:
      question = body.get('question')
      answer = body.get('answer')
      difficulty = body.get('difficulty')
      category = body.get('category')
      if ((question is None) or (answer is None) or (difficulty is None) or (category is None)):
        abort(422)
      try:
        question = Question(
          question = question,
          answer = answer,
          difficulty = difficulty,
          category = category
        )
        question.insert()
        questions =  Question.query.all()
        pagedQuestions = pagination(request, questions)
        return jsonify({
          'success' : True,
          'created' : question.id,
          'question_created': question.question,
          'questions': pagedQuestions,
          'total_questions': len(Question.query.all()),
          'question': question.format()

        })
      except:
        abort(422)
示例#3
0
  def create_question():
      data = request.get_json()
      question = data.get('question', '')
      answer = data.get('answer', '')
      difficulty = data.get('difficulty', '')
      category = data.get('category', '')

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

      question.insert()
      return jsonify({
            'success': True,
             'message': 'Question has been created successfully!'
        }), 200
示例#4
0
    def create_new_question():
        error = False

        # if we're searching for a term
        if request.args:
            search_term = (request.args['term'])
            search_result = Question.query.filter(func.lower(Question.question)\
              .contains(search_term.lower())).all()

            if len(search_result) == 0:
                abort(422)
            else:
                formatted_questions = [
                    question.format() for question in search_result
                ]
                return jsonify({
                    'success': True,
                    'questions': formatted_questions,
                    'total_questions': len(Question.query.all()),
                    'current_category': ""
                })

        # if we're submitting a new question
        elif not request.args:
            try:
                question_to_add = Question(
                    question=request.json['question'],
                    answer=request.json['answer'],
                    category=request.json['category'],
                    difficulty=request.json['difficulty'])
                Question.insert(question_to_add)
            except:
                db.session.rollback()
                error = True
                print(sys.exc_info())
            finally:
                if error:
                    abort(422)
                else:
                    return jsonify({
                        'success': True,
                        'question': question_to_add.format()
                    })
示例#5
0
    def create_question():

        body = request.get_json()

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

        try:
            newquestion = Question(question=question, answer=answer,
                                   difficulty=difficulty,
                                   category=int(category) + 1)
            newquestion.insert()

            return jsonify({'success': True})
        except:

            abort(422)
示例#6
0
 def new_question():
     data = request.get_json()
     if "searchTerm" in data:
         questions = Question.query.filter(
             func.lower(Question.question).like(
                 "%{}%".format(data["searchTerm"].lower())
             )
         ).all()
         formatted_questions = list(map(Question.format, questions))
         result = {
             "questions": formatted_questions,
             "total_questions": len(formatted_questions),
             "current_category": None,
         }
         return jsonify(result)
     else:
         if not (
             data["question"]
             and data["answer"]
             and data["category"]
             and data["difficulty"]
         ):
             abort(422)
         error = False
         try:
             question = Question(
                 question=data["question"],
                 answer=data["answer"],
                 category=data["category"],
                 difficulty=data["difficulty"],
             )
             question.insert()
         except Exception:
             error = True
             db.session.rollback()
             print(exc.info())
         finally:
             db.session.close()
             if error:
                 abort(500)
             else:
                 result = {"success": True}
                 return jsonify(result)
示例#7
0
    def test_delete_question_by_id(self):
        question = Question(
            question="This is a question?",
            category=4,
            difficulty=5,
            answer="This is an answer"
        )
        question.insert()

        res = self.client().delete('/questions/{}'.format(question.id))
        data = json.loads(res.data)

        total_questions = len(Question.query.all())

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['deleted'], question.id)
        self.assertEqual(data['total_questions'], total_questions)
        self.assertTrue(data['questions'])
示例#8
0
    def add_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)
        new_rating = body.get('rating', None)
        search = body.get('search', None)
        try:
            if search:
                selection = Question.query.order_by(Question.id).filter_by(
                    Question.question.ilike('%{}%'.format(search)))

                if selection is None:
                    abort(404)

                current_questions = pagination(request, selection)

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

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

                question = Question(new_question, new_answer, new_category,
                                    new_difficulty, new_rating)
                question.insert()

                selection = __get_questions()
                current_questions = pagination(request, selection)

                return jsonify({
                    'success': True,
                    'current_questions': current_questions,
                    'total_questions': len(selection)
                })
        except:
            abort(422)
示例#9
0
    def create_question():
        '''This endpoint adds a questions based to db
        and checkes for errors.
        
        If an error occured all changes to db are reverted'''

        data = request.get_json()

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

        if (new_question is None or new_answer is None
                or new_difficulty is None or new_category is None):
            abort(422, 'unprocessable')

        question = Question(question=new_question,
                            answer=new_answer,
                            difficulty=new_difficulty,
                            category=new_category,
                            rating=new_rating)
        try:

            question.insert()

            all_questions = Question.query.order_by(Question.id).all()
            paginated_questions = paginate_questions(request, all_questions)

            data = {
                'success': True,
                'created': question.id,
                'question_created': question.question,
                'questions': paginated_questions,
                'questions_count': len(all_questions)
            }

            return jsonify(data)

        except:
            question.rollback()
            abort(400, "bad request")
示例#10
0
    def create_question():
        body = request.get_json()
        new_question = body.get('question', None)
        new_answer = body.get('answer', None)
        new_difficulty = body.get('difficulty', None)
        new_category = body.get('category', None)
        searchTerm = body.get('searchTerm', None)

        current_category = Category.query.filter(
            Category.id == new_category).first()

        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:

                question = Question(question=new_question,
                                    answer=new_answer,
                                    difficulty=new_difficulty,
                                    category=current_category.id)
                question.insert()
                selection = Question.query.order_by(Question.id).all()
                current_questions = paginate_questions(request, selection)

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

        except:
            abort(422)
示例#11
0
    def create_new_question():
        body = request.get_json()
        if body is None:
            abort(400)

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

        if search:
            search_term = f'%{search}%'
            result = Question.query.filter(
                Question.question.ilike(search_term)).order_by(
                    Question.id).all()
            current_questions = paginate_questions(request, result)
            return jsonify({
                'success': True,
                'questions': current_questions,
                'total_questions': len(result),
            })
        if new_question is None or new_answer is None:
            abort(400)

        try:

            question = Question(question=new_question,
                                answer=new_answer,
                                category=new_category,
                                difficulty=new_difficulty)
            question.insert()
            questions = Question.query.order_by(Question.id).all()
            current_questions = paginate_questions(request, questions)
            return jsonify({
                'success': True,
                'created': question.id,
                'questions': current_questions,
                'total_questions': len(questions),
            })
        except BaseException:
            print(sys.exc_info())
            abort(422)
示例#12
0
    def add_question():
        if request.data:
            # data = json.loads(request.data.decode('utf-8'))
            data = request.get_json()
            question = data['question']
            answer = data['answer']
            difficulty = data['difficulty']
            category = data['category']

            if question and answer and difficulty and category:
                new_question = Question(question=question,
                                        answer=answer,
                                        difficulty=difficulty,
                                        category=category)
                Question.insert(new_question)
                result = {"success": True, "data": data}
                return jsonify(result)
            abort(404)
        abort(422)
示例#13
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)
示例#14
0
 def create_question():
     body = request.get_json()
     new_question = body.get('question', None)
     new_answer = body.get('answer', None)
     new_difficulty = body.get('difficulty', None)
     new_category = body.get('category', None)
     if (new_question is None or new_answer is None or new_difficulty is None or new_category is None):
         abort(405)
     else:
         new_Question = Question(
             new_question, new_answer, new_category, new_difficulty)
         new_Question.insert()
         return jsonify({
             "success": True,
             "question": new_Question.question,
             "answer":new_Question.answer,
             "difficulty":new_Question.difficulty,
             "category":new_Question.category
             })
示例#15
0
    def new_question():
        body = request.get_json()

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

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

            # display results
            return jsonify({'success': True, 'question': question.id})
        except:
            abort(422)
示例#16
0
    def create_question():
        body = request.get_json()
        if not body:
            abort(400,
                  {'message': 'request does not contain a valid JSON body.'})
        new_question = body.get('question', None)
        new_category = body.get('category', None)
        new_answer = body.get('answer', None)
        new_difficulty = body.get('difficulty', None)
        if not new_question:

            abort(400, {'message': 'Question can not be blank'})

        if not new_answer:

            abort(400, {'message': 'Answer can not be blank'})

        if not new_category:

            abort(400, {'message': 'Category can not be blank'})

        if not new_difficulty:

            abort(400, {'message': 'Difficulty can not be blank'})
        try:
            user_question = Question(question=new_question,
                                     answer=new_answer,
                                     category=new_category,
                                     difficulty=new_difficulty)
            user_question.insert()
            selection = Question.query.order_by(Question.id).all()
            current_questions = paginate_ques(request, selection)
            categories = Category.query.all()
            categories_all = [category.format() for category in categories]
            return jsonify({
                'success': True,
                'created': user_question.id,
                'questions': current_questions,
                'total_questions': len(Question.query.all()),
                'current_category': categories_all
            })
        except:
            abort(422)
示例#17
0
  def create_question():
    body = request.get_json()

    # new_question = body.get('question', None)
    # new_answer = body.get('answer', None)

    # check if the answer and category are integer value
    try:
      new_difficulty = int(body.get('difficulty', None))
      new_category = int(body.get('category', None))
    except Exception as e:
      abort(422, {'message': str(e)})

    # schema validation
    schema = {'question': {'type': 'string', 'required': True, 'minlength': 5},
              'answer': {'type': 'string', 'required': True, 'minlength': 1},
              'category': {'type': 'integer', 'required': True, 'minlength': 1},
              'difficulty': {'type': 'integer', 'required': True, 'minlength': 1}
              }
    v = Validator(schema)
    # data formated as dict to validate as cerberus validator
    request_data = {'question': body.get('question', None),
                    'answer': body.get('answer', None),
                    'category': new_category,
                    'difficulty': new_difficulty
                    }
    # print(v.validate(request_data))
    # print(v.errors)
    if v.validate(request_data):
      try:
        query = Question(**request_data)
        query.insert()

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

      except Exception as e:
        # print(e)
        abort(422)
    else:
      abort(422, {'message': v.errors})
示例#18
0
    def create_new_question():
      question = request.get_json().get('question')
      answer = request.get_json().get('answer')
      category = request.get_json().get('category')
      difficulty = request.get_json().get('difficulty')

      if not (question and answer and\
         category and difficulty) or not isinstance(question, str)\
           or not isinstance(answer, str) or not isinstance(category, int)\
             or not isinstance(difficulty, int):
        abort(406)

      new_question = Question(question, answer, category, difficulty)
      new_question.insert()
      return jsonify({
        "message": "New question was added.",
        "status": 201,
        "success": True
      }),201
示例#19
0
    def test_get_all_questions_fail(self):
        question = Question(question=self.new_question_1['question'],
                            answer=self.new_question_1['answer'],
                            difficulty=self.new_question_1['difficulty'],
                            category=self.new_question_1['category'])
        question.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().get('/questions', json={'type': 3})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 400)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'bad request')

        question.delete()
        category.delete()
示例#20
0
    def create_question(payload):

        try:
            body = request.get_json()
            search = body.get('searchTerm', None)
            question = body.get('question', None)
            answer = body.get('answer', None)
            difficulty = body.get('difficulty', None)
            category = body.get('category', None)

            if search:

                selection = list(
                    map(
                        Question.format,
                        Question.query.filter(
                            Question.question.ilike('%{}%'.format(search)))))
                current_selection = paginate_questions(request, selection)
                result = {
                    'success': True,
                    'questions': current_selection,
                    'total_questions': len(selection)
                }

                return jsonify(result)

            else:

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

                result = {'success': True, 'new_question': new_question.id}

                return jsonify(result), 200

        except AuthError:
            abort(401)

        except (Exception):
            abort(422)
示例#21
0
    def test_get_questions_paginated_fail(self):
        question = Question(question=self.new_question_1['question'],
                            answer=self.new_question_1['answer'],
                            difficulty=self.new_question_1['difficulty'],
                            category=self.new_question_1['category'])
        question.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().get('/questions?page=1000')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'resource not found')

        question.delete()
        category.delete()
示例#22
0
    def create_new_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)

        search = body.get('searchTerm', None)
        try:
            if search:
                selection = paginate_questions(
                  request, Question.query.order_by(
                    Question.id).filter(Question.question.ilike(
                      '%{}%'.format(search))))
                current_questions = format_questions(selection.all())
                return jsonify({
                    'success': True,
                    'questions': current_questions,
                    'total_questions': len(selection.all()),
                    'current_category': None
                })

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

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

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

        except Exception:
            abort(422)
示例#23
0
    def post_question():

        if request.data:
            # load the request body
            body = request.get_json()
            # load data from body
            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)

        # ensure all fields have data
        else:
            abort(422)

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

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

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

        except:
            # abort unprocessable if exception
            abort(422)
示例#24
0
  def post_question():
      body = request.get_json()



      if (body['question'].strip()=="") or (body['answer'].strip()==""):
          abort(400)
      try:
          new_question = Question(question=body['question'].strip(), answer=body['answer'].strip(),\
          category=body['category'], difficulty=body['difficulty'])
          new_question.insert()

      except:
          abort(422)

      return jsonify({
        'success':True,
        'added': new_question.id
      })
示例#25
0
    def test_delete_question(self):
        """Test delete question"""

        question = Question(question=self.new_question['question'],
                            answer=self.new_question['answer'],
                            category=self.new_question['category'],
                            difficulty=self.new_question['difficulty'])
        question.insert()
        old_total = Question.query.all()
        response = self.client().delete('/questions/{}'.format(int(
            question.id)))
        data = json.loads(response.data)
        new_total = Question.query.all()

        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['deleted'], question.id)
        self.assertEqual(data['total'], len(new_total))
        self.assertTrue(len(new_total) == len(old_total) - 1)
示例#26
0
    def create_question():

        body = request.get_json()

        if len(body) == 1:
            search = body['searchTerm']
            questions_search = Question.query.filter(
                Question.question.ilike('%' + search + '%')).all()
            if len(questions_search) == 0:
                abort(404)
            questions_per_page = pagination(request, questions_search)
            return jsonify({
                'success': True,
                'questions': questions_per_page,
                'total_questions': len(questions_search)
            })
        else:

            try:
                question = body['question']
                answer = body['answer']
                category = body['category']
                difficulty = body['difficulty']

                if len(question) == 0 or len(answer) == 0:

                    abort(400)
                new_question = Question(question=question,
                                        answer=answer,
                                        category=category,
                                        difficulty=difficulty)
                Question.insert(new_question)
                id_new = new_question.id
                questions = Question.query.all()
                categories = Category.query.all()
                questions_per_page = pagination(request, questions)

                dict = {}
                for category in categories:
                    dict[category.id] = category.type
                return jsonify({'success': True, 'created': id_new})
            except:
                abort(422)
示例#27
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()
            return jsonify({
                    'success': True,
                    'message': 'Question successfully created!'
                })
        except:
            abort(422)
示例#28
0
    def test_get_questions_by_category_success(self):
        question = Question(question=self.new_question_1['question'],
                            answer=self.new_question_1['answer'],
                            difficulty=self.new_question_1['difficulty'],
                            category=2)
        question.insert()

        res = self.client().get('/categories/' + question.category +
                                '/questions')
        data = json.loads(res.data)

        question.delete()

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['questions'])
        self.assertEqual(data['total_questions'], 1)
        self.assertTrue(data['categories'])
        self.assertTrue(data['current_category'])
示例#29
0
    def add_question():
        res = request.get_json()
        new_question = res.get('question', None)
        new_question_answer = res.get('answer', None)
        new_question_category = res.get('category', None)
        new_question_dificulty = res.get('difficulty', None)
        try:
            new_question = Question(question=new_question,
                                    answer=new_question_answer,
                                    category=new_question_category,
                                    difficulty=new_question_dificulty)
            new_question.insert()

            return jsonify({
                'success': True,
                'new_question': new_question.format()
            }), 200
        except:
            abort(422)
示例#30
0
    def postQuestion():
        Error = False
        try:
            # myData =  request.get_json()

            question = request.json.get('question')
            category = request.json.get('category')
            difficulty = request.json.get('difficulty')
            answer = request.json.get('answer')
            # addQuestion = Question(myData['question'], myData['Category'], myData['difficulty'], myData['answer'])
            addQuestion = Question(question=question,
                                   answer=answer,
                                   category=category,
                                   difficulty=difficulty)
            addQuestion.insert()
            return jsonify({'success': True, 'question': addQuestion.format()})
        except:
            Error = True
            abort(422)
示例#31
0
    def create_question():

        question = request.json.get('question')
        answer = request.json.get('answer')
        category = request.json.get('category')
        difficulty = request.json.get('difficulty')

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

            return jsonify({
                'success': True,
                'created': question.id,
                'total_question': len(Question.query.all())
            })

        except:
            abort(422)