예제 #1
0
    def post(self):
        """Add new quiz"""
        logs.debug_ ("_________________________________________________")
        logs.debug_ ("QuizzesAPI post fn: %s\nJson Request\n=============\n %s"
                     %(request, request.json))

        userid, username = utls.get_user_from_hdr()
        if 'username' not in session:
            response = handle_invalid_usage(InvalidUsageException
                                ('Error: No active session for this user found', 
                                 status_code=404))
            
            return response

        # Get values from request
        args = self.reqparse.parse_args()
        for key, value in args.iteritems():
            if value is not None:
                if (key == 'title'):
                    title = request.json['title']
                if (key == 'difficulty_level'):
                    difficulty_level = request.json['difficulty_level']
                if (key == 'text'):
                    text = request.json['text']

        # Update tables
        quiz_obj = models.Quiz(title, difficulty_level, text, userid)
        models.db.session.add(quiz_obj)
        models.db.session.commit()
        
        # Return response
        location = "/quizzes/%s" % quiz_obj.qzid
        query_obj = models.Quiz.query.filter_by(qzid=quiz_obj.qzid).all()

        resource_fields =  {'qzid':fields.Integer, 
                           'title':fields.String,
                           'difficulty_level':fields.String,
                           'text':fields.String,
                           'no_ques':fields.Integer
                          }
                            
        quiz = marshal(query_obj, resource_fields)
        response = jsonify(quiz=quiz)
        response.status_code = 201
        response.location = location
        logs.info_(response)
        utls.display_tables()
        return response
예제 #2
0
    def test_quiz(self):
        q1 = models.Question(question='Test Question 1',
                             answers={
                                 'A': 'First Answer',
                                 'B': 'Second Answer'
                             },
                             correct_answer='B')

        q2 = models.Question(question='Test Question 2',
                             answers={
                                 'A': 'An Answer',
                                 'B': 'Another Answer'
                             },
                             correct_answer='A')

        test_quiz = models.Quiz(questions=[q1, q2],
                                code=8675309,
                                name='Test Quiz',
                                userid='test.user-ID')

        key = test_quiz.put()
        result = key.get()
        self.assertDictEqual(
            result.dict, {
                'questions': [{
                    'question': 'Test Question 1',
                    'answers': {
                        'A': 'First Answer',
                        'B': 'Second Answer'
                    }
                }, {
                    'question': 'Test Question 2',
                    'answers': {
                        'A': 'An Answer',
                        'B': 'Another Answer'
                    }
                }],
                'code':
                8675309,
                'name':
                'Test Quiz',
                'userid':
                'test.user-ID'
            })
예제 #3
0
def create_quiz(quiz: schemas.CreateQuizRequest):
    """Create a new quiz
    """
    new_quiz = models.Quiz(quiz.title, quiz.author)
    session.add(new_quiz)
    session.commit()

    for question in quiz.questions:
        new_question = models.Question(new_quiz.id, question.question_text,
                                       question.correct_answer,
                                       question.answer_one,
                                       question.answer_two,
                                       question.answer_three,
                                       question.answer_four)

        session.add(new_question)
    session.commit()
    session.refresh(new_quiz)

    return new_quiz
예제 #4
0
 async def process(a_dir, lang=lang):
     less_counter = LessonCounter()
     if a_dir.startswith('.') or a_dir.startswith('_'):
         return
     path = os.path.abspath('../lesson_source/{}'.format(a_dir)) + '/'
     images = path + 'images'
     path += lang
     l_path = path + '.md'
     e_path = path + '.exercises'
     m_path = path + '.meta'
     q_path = path + '.quiz'
     try:  # lesson generation will be deprecated in future
         with open(l_path) as file:
             html = markdown.markdown(file.read(),
                                      extensions=[
                                          'markdown.extensions.codehilite',
                                          'markdown.extensions.tables'
                                      ])
     except FileNotFoundError:
         return
     with open(m_path) as file:
         meta = yaml.load(file.read())
     meta['author'] = DEFAULT_USER
     meta['file'] = '{}.html'.format(a_dir)
     meta['lesson_no'] = int(a_dir)
     try:
         with open(q_path) as file:
             questions = yaml.load(file.read())
         less_counter.quiz_outcome = 'found'
     except Exception as err:
         questions = False
         less_counter.quiz_outcome = 'none'
     if questions:
         quiz = models.Quiz(title=meta['title'],
                            users=DEFAULT_USER,
                            description=meta['description'])
         quiz_id = await quiz.update_or_create('title')
         meta['quiz'] = quiz_id
         question_order = 1
         for _, val in questions.items():
             try:
                 question = models.Question(**val)
                 qid = await question.update_or_create(*val.keys())
                 qq = models.QuizQuestions(quiz=quiz_id,
                                           question=qid,
                                           question_order=question_order)
                 question_order += 1
                 await qq.update_or_create('question', 'quiz')
                 less_counter.quiz_details_done += 1
             except Exception as err:
                 print(err)
                 less_counter.quiz_details_error += 1
     try:
         lesson = models.Lesson(**meta)
         lid, updated = await lesson.update_or_create('lesson_no',
                                                      verbose=True)
         less_counter.lesson_outcome = 'found'
         if updated:
             less_counter.lesson_outcome = 'updated'
             counter.updated_lessons += 1
         else:
             less_counter.lesson_outcome = 'created'
             counter.added_lessons += 1
     except Exception as err:
         print(err)
         less_counter.lesson_outcome += 'error'
         counter.error_lessons += 1
     try:
         with open(e_path) as file:
             exe = yaml.load(file)
             less_counter.exercise_outcome = 'found'
     except Exception as err:
         exe = False
         less_counter.exercise_outcome = 'not found'
         print(err)
     if exe:
         try:
             for val in exe.values():
                 exercise = models.Exercise(lesson=lid, **val)
                 id, updated = await exercise.update_or_create('title',
                                                               verbose=True)
                 if updated:
                     less_counter.exercise_details_updated += 1
                 else:
                     less_counter.exercise_details_created += 1
         except Exception as err:
             print('error creating exercise')
             less_counter.exercise_details_error += 1
             print(exe)
             print(err)
     dest = os.path.abspath('static/images/')
     if os.path.exists(images):
         for file in os.listdir(images):
             src = os.path.join(images, file)
             if os.path.isfile(src):
                 dst = dest + '/' + file
                 shutil.copy(src, dst)
                 less_counter.lesson_imgs_done += 1
             else:
                 less_counter.lesson_imgs_errors += 1
     return less_counter
예제 #5
0
def load_quizzes():
    """
    Load sample quiz data.
    """
    quiz_list = ['drum_fill_friday.json']

    for quiz in quiz_list:
        with open('www/assets/data/%s' % quiz, 'rb') as readfile:
            quiz_json = dict(json.loads(readfile.read()))

        quiz = {
            'category': "Drum Fill Friday",
            'title': quiz_json['title'],
            'text': 'TKTK',
            'photo': None,
            'seamus_url': '',
            'author': 'Bob Boilen'
        }

        # Create photo
        if quiz_json['photo']:
            quiz['photo'] = _create_photo(quiz_json['photo'])

        # Create quiz
        qz = models.Quiz(**quiz)
        qz.save()

        print "Saved quiz: %s" % qz

        for question_index, question_json in enumerate(quiz_json['questions']):
            question = {
                'order': question_index,
                'quiz': qz,
                'text': question_json['text'],
                'photo': None,
                'audio': None
            }

            # Create photo
            if question_json['photo']:
                question['photo'] = _create_photo(question_json['photo'])

            # Create audio
            if question_json['audio']:
                question['audio'] = _create_audio(question_json['audio'])

            # Create question
            qn = models.Question(**question)
            qn.save()

            print "Saved question: %s" % qn

            for choice_index, choice_json in enumerate(
                    question_json['choices']):
                choice = {
                    'order': choice_index,
                    'question': qn,
                    'text': choice_json['text'],
                    'correct_answer': False,
                    'photo': None,
                    'audio': None,
                }

                if choice_index == question_json['answer']:
                    choice['correct_answer'] = True

                # Create photo
                if choice_json['photo']:
                    choice['photo'] = _create_photo(choice_json['photo'])

                # Create audio
                if choice_json['audio']:
                    choice['audio'] = _create_audio(choice_json['audio'])

                # Create choice
                ch = models.Choice(**choice)
                ch.save()

                print 'Saved choice: %s' % ch

        qz.deploy()
        print 'Deployed quiz: %s' % qz
예제 #6
0
 async def process(a_dir, lang=lang):
     if a_dir.startswith('.') or a_dir.startswith('_'):
         return
     path = os.path.abspath('lesson_source/{}'.format(a_dir)) + '/'
     images = path + 'images'
     path += lang
     l_path = path + '.md'
     e_path = path + '.exercises'
     m_path = path + '.meta'
     q_path = path + '.quiz'
     try:
         with open(l_path) as file:
             html = markdown.markdown(
                 file.read(), extensions=['markdown.extensions.codehilite'])
     except FileNotFoundError:
         return
     with open('static/lessons/{}.html'.format(a_dir), 'w') as file:
         file.write(HEADER + html + FOOTER)
     with open(m_path) as file:
         meta = yaml.load(file.read())
     meta['author'] = 1
     meta['file'] = '{}.html'.format(a_dir)
     try:
         with open(q_path) as file:
             questions = yaml.load(file.read())
         print('found quiz')
     except Exception as err:
         questions = False
         print(err)
     if questions:
         quiz = models.Quiz(title=meta['title'],
                            users=14,
                            description=meta['description'])
         quiz_id = await quiz.update_or_create('title')
         meta['quiz'] = quiz_id
         question_order = 1
         for _, val in questions.items():
             qustion = models.Question(**val)
             qid = await qustion.update_or_create(*val.keys())
             qq = models.QuizQuestions(quiz=quiz_id,
                                       question=qid,
                                       question_order=question_order)
             question_order += 1
             await qq.update_or_create('question', 'quiz')
             print('question created')
     lesson = models.Lesson(**meta)
     lid = await lesson.update_or_create(*meta.keys())
     try:
         with open(e_path) as file:
             exe = yaml.load(file.read())
     except:
         exe = False
     if exe:
         try:
             for _, val in exe.items():
                 exercise = models.Exercise(lesson=lid, **val)
                 await exercise.update_or_create(*val.keys())
         except Exception as err:
             print('error creating exercise')
             print(exe)
             print(val)
             print(err)
     dest = os.path.abspath('static/images/')
     if os.path.exists(images):
         for file in os.listdir(images):
             src = os.path.join(images, file)
             if os.path.isfile(src):
                 dst = dest + '/' + file
                 shutil.copy(src, dst)
                 print(src + ' copied')
             else:
                 print(src + ' NOT copied')
예제 #7
0
def db_init():

    models.db.drop_all()
    models.db.create_all()
    utls.display_tables()

    #populate Quiz table
    qz1 = models.Quiz( "Python Basics  ", "Simple  ", "Explanation", 1, 2)
    qz2 = models.Quiz( "Python Advanced", "Moderate", "No text    ", 1)
    models.db.session.add_all([qz1,qz2])

    #populate models.Questions table
    #Quiz 1
    ques1 = models.Question("What does 'def foo(): pass do", 
                     "A fn which does nothing",1,1)
    ques2 = models.Question("Is python an OOP l           ", 
                     "Yes python is an OOP l",1,1)
    ques3 = models.Question("What is operator overloading?", 
                     "Operator overloading is a concept in OOPS",1,1)
    ques4 = models.Question("Is python dynmaically typed? ", 
                     "Yes python is a dynmaically typed language",1,1)
    models.db.session.add_all([ques1, ques2, ques3, ques4])

    #Quiz 1
    ques5 = models.Question("What is the use of an assertion?",
                     "A fn which does nothing",2,1)
    ques6 = models.Question("What is python library scrapy used for?",
                     "Yes python is an OOP l",2,1)
    models.db.session.add_all([ques5, ques6])

    #populate Answer choices table
    #Quiz 1
    ans1  = models.Anschoice(1, 1, "(a) This function does nothing      ", True)
    ans2  = models.Anschoice(1, 1, "(b) This function returns a fn pass ", False)
    ans3  = models.Anschoice(1, 1, "(c) This function is not yet defined", False)
    ans4  = models.Anschoice(1, 2, "(a) Yes Python is object oriented   ", True)
    ans5  = models.Anschoice(1, 2, "(b) No Python is not object oriented", False)
    ans6  = models.Anschoice(1, 2, "(c) Python may not be used as OOP l ", False)
    ans7  = models.Anschoice(1, 3, "(a) This function does nothing      ", True)
    ans8  = models.Anschoice(1, 3, "(b) This function returns a fn pass ", False)
    ans9  = models.Anschoice(1, 3, "(c) This function is not yet defined", False)
    ans10  = models.Anschoice(1, 4, "(a) Yes Python is object oriented   ", True)
    ans11  = models.Anschoice(1, 4, "(b) No Python is not object oriented", False)
    ans12  = models.Anschoice(1, 4, "(c) Python may not be used as OOP l ", False)
    models.db.session.add_all([ans1, ans2, ans3, ans4, ans5, ans6, ans7, ans8,\
                        ans9, ans10, ans11, ans12])
    #Quiz 2
    ans13  = models.Anschoice(2, 5, "(a) This function does nothing      ", False)
    ans14  = models.Anschoice(2, 5, "(b) This function returns a fn pass ", True)
    ans15  = models.Anschoice(2, 5, "(c) This function is not yet defined", False)
    ans16  = models.Anschoice(2, 6, "(a) Yes Python is object oriented   ", False)
    ans17  = models.Anschoice(2, 6, "(b) No Python is not object oriented", True)
    ans18  = models.Anschoice(2, 6, "(c) Python may not be used as OOP l ", False)
    models.db.session.add_all([ans13, ans14, ans15, ans16, ans17, ans18])
    try:
        models.db.session.commit()
    except IntegrityError:
        print "Arch: Caught SQL Alchemy exception Integrity Error"
    except InvalidRequestError:
        print "Arch: Caught SQL Alchemy exception InvalidRequestError"

    return None