예제 #1
0
    def post(self):
        name = request.get_json()['name']
        group = session.query(QuestionGroup).filter_by(name=name).first()
        if group is None:
            return dict()

        return dict(error=True, message='Zbiór o takiej nazwie już istnieje.')
예제 #2
0
    def post(self):
        try:
            data = request.get_json()
            question_ids = data['questions']
            display_mode = data['displayMode']

            # TODO: constants
            has_valid_ids = isinstance(question_ids,
                                       list) and 9 < len(question_ids) < 101
            has_valid_display_mode = display_mode in [
                'single', 'multiple', 'variable'
            ]
            if not has_valid_ids or not has_valid_display_mode:
                raise InvalidRequest

            questions = session.query(Question).filter(
                Question.id.in_(question_ids))
            exam = Exam(user_id=current_user.id,
                        display_mode=display_mode,
                        created_at=datetime.utcnow())
            exam.questions = questions.all()

            session.add(exam)
            session.commit()

            return dict(id=exam.id)
        except KeyError:
            raise InvalidRequest
예제 #3
0
    def post(self):
        data = request.get_json()
        username_id = data.get('usernameId')

        username = session.query(Username).filter(
            Username.id == username_id).first()
        if username is None:
            raise InvalidRequest

        is_taken = session.query(User).filter(
            User.username_id == username_id).first() is not None
        if is_taken:
            return error(USERNAME_TAKEN)

        current_user.username = username
        session.commit()
        return dict()
예제 #4
0
 def find_by_id(cls, object_id: Union[list, int], only_query=False):
     if not hasattr(cls, 'id'):
         raise AttributeError('{} does not have an id attribute.'.format(
             cls.__name__))
     is_list = isinstance(object_id, list)
     query = session.query(cls)
     query = query.filter(
         cls.id.in_(object_id)) if is_list else query.filter_by(
             id=object_id)
     if only_query:
         return query
     return query.all() if is_list else query.first()
예제 #5
0
    def get(self):
        usernames_alias = aliased(Username)
        subquery = (select(
            [func.count(1).label('count')]).select_from(User).where(
                and_(User.id != current_user.id,
                     User.username_id == usernames_alias.id)).as_scalar())

        usernames = session.query(usernames_alias).filter(
            subquery == 0).order_by(usernames_alias.content)
        schema = UsernameSchema()

        return [schema.dump(u) for u in usernames]
예제 #6
0
    def get(self):
        correct_session_answers = (session.query(Answer).join(Question).join(
            ExamQuestion).join(Exam).join(ExamSession).filter(
                and_(Answer.correct.is_(True),
                     ExamSession.user_id == current_user.id,
                     ExamSession.submitted.is_(True))).count())

        user_correct_session_answers = (session.query(ExamSessionAnswer).join(
            Answer).join(ExamSession).filter(
                and_(Answer.correct.is_(True)),
                ExamSession.user_id == current_user.id,
                ExamSession.submitted.is_(True)).count())

        total_exam_sessions = (session.query(ExamSession).filter(
            ExamSession.user_id == current_user.id).count())

        submitted_exam_sessions = (session.query(ExamSession).filter(
            and_(ExamSession.user_id == current_user.id,
                 ExamSession.submitted.is_(True))).count())

        answered_questions = (
            session.query(ExamSessionAnswer).join(ExamSession).filter(
                ExamSession.user_id == current_user.id).count())

        correct_answered_questions = (session.query(ExamSessionAnswer).join(
            ExamSession).join(Answer).filter(
                and_(ExamSession.user_id == current_user.id,
                     Answer.correct.is_(True))).count())

        return dict(correct_session_answers=correct_session_answers,
                    user_correct_session_answers=user_correct_session_answers,
                    total_exam_sessions=total_exam_sessions,
                    submitted_exam_sessions=submitted_exam_sessions,
                    answered_questions=answered_questions,
                    correct_answered_questions=correct_answered_questions)
예제 #7
0
    def post(self):
        data = request.get_json()
        question = data['question']

        db_question = session.query(Question).get(question['id'])
        admin_group = session.query(QuestionGroup).get(
            db_question.admin_group_id)

        can_edit, reason = can_edit_admin_group(admin_group)
        if not can_edit:
            return reason

        tags = process_tags([question])

        questions = substitute_tags([question], tags)

        for question in questions:
            update_question_in_db(question, admin_group)

        # SearchIndex.rebulid_for_tags([t.id for t in db_question.tags])
        session.commit()
        return dict()
예제 #8
0
    def post(self):
        data = request.get_json()
        name = data['name']
        questions = data['questions']

        admin_group = session.query(QuestionGroup).filter_by(name=name).first()

        can_edit, reason = can_edit_admin_group(admin_group)
        if not can_edit:
            return reason

        tags = process_tags(questions)
        questions = substitute_tags(questions, tags)

        for question in questions:
            update_question_in_db(question, admin_group)

        session.commit()
        return dict()
예제 #9
0
def process_tags(questions):
    question_tags = [q['tags'] for q in questions]
    unique_tags = list(
        set([tag['name'] for tag_list in question_tags for tag in tag_list]))
    tags = session.query(Tag).filter(
        or_(Tag.name.in_(unique_tags),
            Tag.aliases.any(TagAlias.name.in_(unique_tags)))).all()
    new_tags = []
    for t in unique_tags:
        exists = False
        for tag in tags:
            if t == tag.name:
                exists = True
            if t in [a.name for a in tag.aliases]:
                exists = True
        if not exists:
            tg = Tag(name=t)
            new_tags.append(tg)
    return tags + new_tags
예제 #10
0
    def post(self):
        try:
            data = request.get_json()
            name = data['name']
            questions = data['questions']
            admin_group = QuestionGroup(user_id=current_user.id, name=name)

            if session.query(QuestionGroup).filter_by(
                    name=name).first() is not None:
                return dict(error=True,
                            message='Ta nazwa zbioru jest już zajęta.')

            tags = process_tags(questions)
            questions = substitute_tags(questions, tags)

            for question in questions:
                qst = Question(content=question['content'],
                               admin_group=admin_group)
                for tag in question['tags']:
                    qst.tags.append(tag)
                for answer in question['answers']:
                    qst.answers.append(
                        Answer(content=answer['content'],
                               correct=answer['correct']))
                for choice in question['choices']:
                    qst.choices.append(
                        Choice(identifier=choice['identifier'],
                               content=choice['content']))
                session.add(qst)

            session.commit()

            SearchIndex.register_questions(admin_group.questions)

            return dict()
        except KeyError:
            return invalid_request()
예제 #11
0
 def get_all(cls, only_query=True):
     data = session.query(cls)
     return data if only_query else data.all()
예제 #12
0
    def get(self):
        max_row = request.args.get('maxRow')
        max_row = 0 if max_row is None else max_row

        exams = session.query(Exam.id.label('exam_id'),
                              null().label('session_id'),
                              Exam.created_at.label('date')).filter(
                                  Exam.user_id == current_user.id)

        sessions = session.query(
            null().label('exam_id'), ExamSession.id.label('session_id'),
            case([(ExamSession.submitted, ExamSession.submitted_at)],
                 else_=ExamSession.created_at).label('date')).filter(
                     ExamSession.user_id == current_user.id)

        queries = union(exams, sessions).alias()

        all_activity = session.execute(
            select([func.count().label('count_1')]).select_from(queries))
        total = all_activity.first().count_1
        del all_activity

        activity = select([
            func.row_number().over(
                order_by=queries.c.date.desc()).label('row_number'),
            queries.c.exam_id, queries.c.session_id, queries.c.date
        ])

        alias = activity.alias()
        activity = session.execute(
            select(['*']).select_from(alias).where(
                alias.c.row_number > max_row).limit(PAGE_SIZE))

        items = []
        last_activity = None
        for last_activity in activity:
            items.append(last_activity)

        if len(items) == 0:
            return dict(items=[], max_row=-1, total=0)

        exam_ids = [a.exam_id for a in items if a.exam_id is not None]
        exams = session.query(Exam).filter(
            Exam.id.in_(exam_ids)).all() if len(exam_ids) > 0 else []

        session_ids = [a.session_id for a in items if a.session_id is not None]

        sessions = session.query(ExamSession).filter(ExamSession.id.in_(session_ids)).all() \
            if len(session_ids) > 0 else []

        exam_schema = ExamSchema()
        session_schema = ExamSessionSchema()

        def dump(item):
            data = dict(
                date=item.date.replace(tzinfo=timezone.utc).isoformat(),
                row_number=item.row_number)
            if item.exam_id is not None:
                data.update(
                    dict(data=exam_schema.dump(
                        [e for e in exams if e.id == item.exam_id][0]),
                         type='exam_created'))
            else:
                exam_session = [
                    s for s in sessions if s.id == item.session_id
                ][0]
                data.update(
                    dict(data=session_schema.dump(exam_session),
                         type='session_submitted'
                         if exam_session.submitted else 'session_created'))
            return data

        return dict(items=[dump(i) for i in items],
                    max_row=last_activity.row_number,
                    total=total)
예제 #13
0
 def find_by_email(email):
     return session.query(User).filter(User.email == email).first()
예제 #14
0
 def reset_verification_code_attempts():
     for user in session.query(User):
         user.verification_attempts = 0
         user.password_reset_code = None
         user.password_reset_attempts = 0
         session.commit()
예제 #15
0
    def get(self, exam_id):
        exam = session.query(Exam).filter_by(id=exam_id).first()

        return dict(data=ExamSchema().dump(exam))