コード例 #1
0
 def post(self):
     try:
         counter = 0
         data = request.get_json(force=True)
         #print(data)
         num = int(data['correctAnswerNum'])
         new_question = QuestionModel(name=data['name'],
                                      description=data['description'],
                                      difficulty=data['difficulty'],
                                      category_id=data['category_id'])
         new_question.flush_db()
         questionId = new_question.id
         new_question.save_to_db()
         data = data['answers']
         #print(questionId)
         for answer in data:
             if counter == num:
                 new_answer = AnswersModel(question_id=questionId,
                                           answer=answer,
                                           correct='1')
             else:
                 new_answer = AnswersModel(question_id=questionId,
                                           answer=answer,
                                           correct='0')
             new_answer.save_to_db()
             counter += 1
         return {'response': 'Succesfull'}, 200
     except Exception as e:
         print('ez a hiba', e)
         return {'response': 'Invalid data'}, 400
コード例 #2
0
    def put(self, quiz_id, question_id):
        data = parser.parse_args()
        data['quiz_id'] = quiz_id

        question = QuestionModel.find_by_id(question_id)

        if question is None:
            new_question = QuestionModel(**data)
            try:
                new_question.save()

                return new_question.json(), 201
            except:
                return {
                    "message": "An error occurred while inserting Question."
                }, 500

        try:
            question.update(**data)
        except:
            return {
                "message": "An error occurred while updating Question."
            }, 500

        return question.json(), 200
コード例 #3
0
    def post(self, quiz_id):
        data = parser.parse_args()
        data['quiz_id'] = quiz_id

        question = QuestionModel(**data)
        try:
            question.save()
        except:
            return {
                "message": "An error occurred while inserting Question."
            }, 500

        return question.json(), 201
コード例 #4
0
    def post(self, id):
        if QuestionModel.find_by_id(id):
            return {
                'message': "A question with id '{}' already exists.".format(id)
            }, 400

        question = QuestionModel(id)
        try:
            question.save_to_db()
        except:
            return {"message": "An error occurred creating the question."}, 500

        return question.json(), 201
コード例 #5
0
    def post(self):
        parser = self.default_parser
        parser.add_argument('evaluation', type=int, required=True, help="A question needs an evaluation")
        parser.add_argument('author', type=str, required=True, help="A question needs an author")
        data = parser.parse_args()

        question = QuestionModel(**data)

        try:
            question.save_to_db()
        except Exception as e:
            return dict(message='something goes wrong with your insert db action', error=e.args)

        return question.json(), 201
コード例 #6
0
    def post(self):
        # parse_args() return only arguments added by add_argument as Namespace
        # Any missing added argument will stop and return help message to the browser
        data = Question.parser.parse_args()

        # data namespace is rolled into one argument (**data)
        question = QuestionModel(**data)

        try:
            question.save_to_db()
        except:
            return {"message": "An error occurred inserting the item."}, 500

        return question.json(), 201
コード例 #7
0
    def post(self):
        # parse_args() return only arguments added by add_argument as Namespace
        # Any missing added argument will stop and return help message to the browser
        data = Quiz.parser.parse_args()

        # Save data into Quiz table
        quiz = QuizModel(data["quiz_name"], data["theme_id"])

        try:
            quiz.save_to_db()
        except:
            return {"message": "An error occurred inserting the item."}, 500

        # Save data into Question table
        questions = data["questions"]
        for q in questions:
            question = QuestionModel(quiz.quiz_id, q["question_category"],
                                     q["questiontype_id"],
                                     q["question_statement"],
                                     q["question_correct_entries"],
                                     q["question_wrong_entries"])

            try:
                question.save_to_db()
            except:
                return {
                    "message": "An error occurred inserting the question."
                }, 500

            # Save data into Question table
            answers = q["answers"]
            for a in answers:
                answer = AnswerModel(question.question_id,
                                     a["answer_is_correct"],
                                     a["answer_statement"])

                try:
                    answer.save_to_db()
                except:
                    return {
                        "message": "An error occurred inserting the answer."
                    }, 500

        return quiz.json(), 201
コード例 #8
0
    def put(self, question_id):
        data = Question.parser.parse_args()

        question = QuestionModel.find_by_id(question_id)

        if question is None:  # Create a new question if it does not exist in the database
            question = QuestionModel(**data)
        else:  # Update the question if it exists in the database
            question.quiz_id = data['quiz_id']
            question.question_category = data['question_category']
            question.questiontype_id = data['questiontype_id']
            question.question_statement = data['question_statement']
            question.question_correct_entries = data[
                'question_correct_entries']
            question.question_wrong_entries = data['question_wrong_entries']
            question.question_update = datetime.now()

        question.save_to_db()

        return question.json()
コード例 #9
0
    def post(self, qa_id):
        session = QaModel.get_by_id(qa_id)

        ##If sesssion exists, is ongoing, and question doesnt exist, allow posting question, else error
        if session:
            if not session.is_ongoing():
                return {"message": "This session is not currently active"}, 400

            request_data = Question.parser.parse_args()

            if request_data["text"] == "" or request_data[
                    "asked_by_user"] == "":
                return {
                    "message":
                    "Please fill all required fields, they cannot be empty"
                }, 400

            if QuestionModel.question_exists(
                    qa_id, request_data["text"].strip(),
                    request_data["asked_by_user"].strip()):
                return {
                    "message": "This question already exists for this session"
                }, 400

            question = QuestionModel(qa_id, request_data["text"].strip(),
                                     request_data["asked_by_user"].strip())

            try:
                question.save_to_db()
            except Exception as e:
                print(str(e))
                return {
                    "message": "An error occurred while posting the question."
                }, 500
        else:
            return {"message": "The session was not found"}, 404

        #return object json representation if request was successful
        return question.json(), 201
コード例 #10
0
def test_db():
    from models.user import UserModel, RoleModel

    student = RoleModel('student')
    instructor = RoleModel('instructor')
    db.session.add_all([student, instructor])
    db.session.commit()
    bart = UserModel('bart',
                     'bart',
                     'bart',
                     'student',
                     firstname=None,
                     lastname=None,
                     picture=None)
    lisa = UserModel('lisa',
                     'lisa',
                     'lisa',
                     'student',
                     firstname=None,
                     lastname=None,
                     picture=None)
    millhouse = UserModel('millhouse',
                          'millhouse',
                          'millhouse',
                          'student',
                          firstname=None,
                          lastname=None,
                          picture=None)
    edna = UserModel('edna',
                     'edna',
                     'edna',
                     'instructor',
                     firstname=None,
                     lastname=None,
                     picture=None)
    simour = UserModel('simour',
                       'simour',
                       'simour',
                       'instructor',
                       firstname=None,
                       lastname=None,
                       picture=None)
    db.session.add_all([bart, lisa, millhouse, edna, simour])
    db.session.commit()
    print('::: test roles and users ::: ok')
    ###################
    print('students')
    for student in student.users:
        print('>>> {}'.format(student.username))
    print('instructors')
    for instructor in instructor.users:
        print('>>> {}'.format(instructor.username))
    ###################

    from models.course import CourseModel
    from models.category import CategoryModel

    maths = CategoryModel('maths', fr_label=None, en_label=None, picture=None)
    english = CategoryModel('english',
                            fr_label=None,
                            en_label=None,
                            picture=None)
    db.session.add_all([maths, english])
    db.session.commit()
    math_course = CourseModel('mathematics',
                              'basic operations',
                              simour.id,
                              maths.id,
                              picture=None)
    english_course = CourseModel('english',
                                 'grammar',
                                 edna.id,
                                 english.id,
                                 picture=None)
    db.session.add_all([math_course, english_course])
    db.session.commit()
    math_course.register_student(bart.id)
    math_course.register_student(lisa.id)
    english_course.register_student(lisa.id)
    english_course.register_student(millhouse.id)
    db.session.commit()
    print('::: test categories and courses ::: ok')
    ###################
    print('students enrolled in math')
    for student in math_course.students:
        print('>>> {}'.format(student.username))
    print('author of math_course')
    print('>>> {}'.format(math_course.author.username))
    print('edna published courses')
    for course in edna.published_courses:
        print('>>> {} - {}'.format(course.title, course.category.name))
    ###################

    from models.chapter import ChapterModel
    from models.quiz import QuizModel
    from models.question import QuestionModel
    from models.answer import AnswerModel

    chapter1 = ChapterModel('adds', '2 + 2 = 4', 1, math_course.id)
    chapter2 = ChapterModel('subs', '2 - 2 = 0', 2, math_course.id)
    db.session.add_all([chapter1, chapter2])
    db.session.commit()
    quiz1 = QuizModel('first grade', 1, math_course.id)
    quiz2 = QuizModel('second grade', 2, math_course.id)
    db.session.add(quiz1)
    db.session.add(quiz2)
    db.session.commit()
    question1 = QuestionModel('1 + 1?', 1, 2, quiz1.id)
    db.session.add(question1)
    db.session.commit()
    answer1 = AnswerModel('0', 1, question1.id)
    db.session.add(answer1)
    answer2 = AnswerModel('2', 2, question1.id)
    db.session.add(answer2)
    question2 = QuestionModel('3 - 1?', 2, 1, quiz1.id)
    db.session.add(question2)
    answer3 = AnswerModel('2', 1, question2.id)
    db.session.add(answer3)
    answer4 = AnswerModel('4', 2, question2.id)
    db.session.add(answer4)
    db.session.commit()
    print('::: test chapters and quizzes and questions and answers ::: ok')
    ###################
    print('chapters in math_course')
    for chapter in math_course.chapters:
        print('>>> {}'.format(chapter.title))
    print('quizzes in math_course')
    for quiz in math_course.quizzes:
        print('>>> {}'.format(quiz.title))
    print('questions in quiz1')
    for question in quiz1.questions:
        print('>>> {}'.format(question.question))
    print('answers in question1')
    for answer in question1.answers:
        print('>>> {}'.format(answer.answer))
    print('for question1 the good answer is number {}'.format(
        question1.good_answer))
    current_question = question1.question
    good_answer = AnswerModel.query.filter_by(
        number=question1.good_answer).first()
    print('question: {} | response: {}'.format(current_question,
                                               good_answer.answer))
    ###################

    from models.comment import CommentModel
    from models.rating import RatingModel

    comment1 = CommentModel('hay caramba', 'hay caramba', math_course.id,
                            bart.id)
    comment2 = CommentModel('retention', 'retention', math_course.id,
                            simour.id)
    comment3 = CommentModel('eat my short', 'eat my short', math_course.id,
                            bart.id)
    db.session.add_all([comment1, comment2, comment3])
    db.session.commit()
    rate1 = RatingModel(5, english_course.id, lisa.id)
    rate2 = RatingModel(3, english_course.id, millhouse.id)
    db.session.add_all([rate1, rate2])
    db.session.commit()
    print('::: test comments and ratings ::: ok')
    ###################
    print('comments in math_course')
    for comment in math_course.comments:
        print('>>> {} by {}'.format(comment.title, comment.author.username))
    print('ratings in english_course')
    for rate in english_course.ratings:
        print('>>> {}/5 by {}'.format(rate.rate, rate.author.username))
    ###################

    from models.badge import BadgeModel
    from models.score import ScoreModel

    score = ScoreModel(2, 2, lisa.id, quiz1.id)
    db.session.add(score)
    db.session.commit()
    badge = BadgeModel('honor', math_course.id, lisa.id)
    db.session.add(badge)
    db.session.commit()
    print('::: test scores and badges ::: ok')
    ###################
    print('badges earned by lisa')
    for badge in lisa.badges:
        print('>>> {}'.format(badge.name))
    print('scores in quiz1')
    for score in quiz1.scores:
        print('>>> {} by {}'.format(score.score, score.student.username))