示例#1
0
    def retrieve(self, request, *args, **kwargs):
        exam_paper = self.get_object()
        serializer = ExamPaperSerializer(exam_paper)

        if exam_paper.create_type == 'random':
            section_ids = exam_paper.rules.values_list('problem_section_id',
                                                       flat=True)
            post_data = {
                'sections':
                list(section_ids),
                'types':
                ['multiplechoiceresponse', 'choiceresponse', 'stringresponse']
            }

            token = request.user.social_auth.first(
            ).extra_data[u'access_token']
            url = settings.EDX_API['HOST'] + settings.EDX_API[
                'SECTION_PROBLEMS']
            rep = requests.post(url,
                                json=post_data,
                                headers={'Authorization': 'Bearer ' + token})

            all_problems = self.generate_random_problem(
                exam_paper.rules.all(), rep.json())

            res_data = serializer.data
            res_data['problems'] = all_problems

            return Response(response_format(res_data))

        return Response(response_format(serializer.data))
示例#2
0
    def create(self, request, *args, **kwargs):
        """
        参加考试-更新考试时间,更改考试状态
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        participant_id = request.data['participant_id']

        exam_participant = ExamParticipant.objects.filter(
            id=participant_id).first()
        if not exam_participant:
            return Response(response_format(data=[], msg='考试任务不存在'))
        exam_task = self.get_exam_task(exam_participant)
        if exam_participant and exam_task:
            if not exam_participant.participate_time:
                exam_participant.participate_time = datetime.datetime.now()
                # exam_participant.hand_in_time = datetime.datetime.now() + datetime.timedelta(minutes=exam_task.exam_time_limit)
            if exam_participant.task_state == TASK_STATE[0][0]:
                exam_participant.task_state = TASK_STATE[1][0]
            with transaction.atomic():
                exam_participant.save()

            return Response(response_format(data=[], msg='开始考试'))
        else:
            return Response(response_format(data=[], msg='考试任务不存在'))
示例#3
0
    def update(self, request, *args, **kwargs):
        """
        「考试中」和「考试结束」不可编辑
        """
        instance = self.get_object()
        if instance.task_state in (TASK_STATE[1][0], TASK_STATE[2][0]):
            return Response(response_format(msg='Can not edit started task'))

        request.data['creator'] = request.user.id

        partial = kwargs.pop('partial', False)
        serializer = self.get_serializer(instance,
                                         data=request.data,
                                         partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        tasks.start_exam_task.apply_async([instance.id],
                                          eta=instance.period_start)
        return Response(response_format(serializer.data))
示例#4
0
    def list(self, request, *args, **kwargs):
        try:
            participant_id = int(str(self.request.GET.get('participant_id')))
        except Exception as ex:
            participant_id = 0
        queryset = self.filter_queryset(self.get_queryset())

        serializer = self.get_serializer(queryset, many=True)
        if len(serializer.data) == 0:
            return Response(
                response_format(data=serializer.data, msg='考试不存在', status=-1))
        else:
            exam_participant = ExamParticipant.objects.filter(
                id=participant_id).first()
            if exam_participant:
                if exam_participant.task_state == TASK_STATE[1][0]:
                    # 正在考试中
                    common_info = self.get_exam_task_info(exam_participant)
                    data = self.get_started_data(serializer)
                    return self.get_return_response(data, **common_info)
                elif exam_participant.task_state == TASK_STATE[2][0]:
                    # 考试结束
                    common_info = self.get_exam_task_info(exam_participant)
                    data = self.get_finished_data(serializer)
                    return self.get_return_response(data, **common_info)
                elif exam_participant.task_state == TASK_STATE[0][0]:
                    return Response(
                        response_format(data=[], msg='考试未开始', status=-1))
                else:
                    return Response(
                        response_format(data=[], msg='试卷失效', status=-2))
            else:
                return Response(
                    response_format(data=[], msg='考试未添加参与者', status=-3))
示例#5
0
 def create(self, request, *args, **kwargs):
     """
     提交试卷
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     participant_id = str(self.request.data['participant_id'])
     exam_participant = ExamParticipant.objects.filter(
         id=participant_id).first()
     if not exam_participant:
         return Response(response_format(data=[], msg='考试不存在', status=-1))
     if exam_participant.exam_task == TASK_STATE[1][0]:
         problems = ExamParticipantAnswerSerializer(
             request.data['problems'])
         exam_participant_answers = ExamParticipantAnswer.objects.filter()
         with transaction.atomic():
             for problem in problems.instance:
                 exam_participant_answer = exam_participant_answers.filter(
                     id=str(problem['id'])).first()
                 if exam_participant_answer:
                     exam_participant_answer.answer = str(problem['answer'])
                     exam_participant_answer.save()
             exam_participant.task_state = TASK_STATE[2][0]
             # TODO
             exam_participant.exam_result = EXAM_RESULT[1][0]
             exam_participant.save()
     else:
         return Response(response_format(data=[], msg='只有考试中的试卷允许提交'))
     return Response(response_format(data=[], msg='提交成功'))
示例#6
0
    def destroy(self, request, *args, **kwargs):
        """
        「考试中」的任务不能删除操作;
        """
        instance = self.get_object()
        if instance.task_state == TASK_STATE[1][0]:
            return Response(response_format(msg='Can not delete started task'))

        self.perform_destroy(instance)
        return Response(response_format())
示例#7
0
 def get(self, request, course_id, *args, **kwargs):
     token = request.user.social_auth.first().extra_data['access_token']
     url = settings.EDX_API['HOST'] + settings.EDX_API['COURSE_SECTIONS']
     payload = {'course_id': course_id}
     rep = requests.get(url,
                        headers={'Authorization': 'Bearer ' + token},
                        params=payload)
     if rep.status_code == 400:
         return Response(
             response_format(status=rep.json().get('code'),
                             msg=rep.json().get('msg')))
     else:
         return Response(response_format(rep.json()))
示例#8
0
 def post(self, request, *args, **kwargs):
     token = request.user.social_auth.first().extra_data['access_token']
     url = settings.EDX_API['HOST'] + settings.EDX_API['PROBLEM_DETAIL']
     post_data = {'problems': request.data.get('problems')}
     rep = requests.post(url,
                         headers={'Authorization': 'Bearer ' + token},
                         json=post_data)
     if rep.status_code == 400:
         return Response(
             response_format(status=rep.json().get('code'),
                             msg=rep.json().get('msg')))
     else:
         return Response(response_format(rep.json()))
示例#9
0
    def duplicate(self, request, pk, *args, **kwargs):
        exam_paper = self.get_object()

        name = exam_paper.name
        new_name = name + DUPLICATE_SUFFIX
        if len(new_name) > MAX_PAPER_NAME_LENGTH:
            raise ValidationError(
                detail='Ensure this field has no more than %d characters.' %
                MAX_PAPER_NAME_LENGTH)

        exam_paper.pk = None
        exam_paper.name = new_name
        exam_paper.created = timezone.now()
        exam_paper.modified = timezone.now()
        exam_paper.creator = self.request.user
        exam_paper.save()

        problems = exam_paper.problems.all()
        rules = exam_paper.rules.all()
        with transaction.atomic():
            for problem in problems:
                problem.pk = None
                problem.exam_paper = exam_paper
                problem.save()

            for rule in rules:
                rule.pk = None
                rule.exam_paper = exam_paper
                rule.save()

        return Response(response_format())
示例#10
0
    def duplicate(self, request, pk, *args, **kwargs):
        exam_paper = self.get_object()
        name = exam_paper.name
        problems = exam_paper.problems.all()
        rules = exam_paper.rules.all()

        exam_paper.pk = None
        exam_paper.name = name + DUPLICATE_SUFFIX
        exam_paper.created = timezone.now()
        exam_paper.modified = timezone.now()
        exam_paper.creator = self.request.user

        exam_paper.save()

        with transaction.atomic():
            for problem in problems:
                problem.pk = None
                problem.exam_paper = exam_paper
                problem.save()

            for rule in rules:
                rule.pk = None
                rule.exam_paper = exam_paper
                rule.save()

        return Response(response_format())
 def get_paginated_response(self, data):
     return Response(
         response_format(
             OrderedDict([('count', self.page.paginator.count),
                          ('next', self.get_next_link()),
                          ('previous', self.get_previous_link()),
                          ('results', data)])))
示例#12
0
 def get(self, request, *args, **kwargs):
     token = request.user.social_auth.first().extra_data['access_token']
     url = settings.EDX_API['HOST'] + settings.EDX_API['COURSES']
     rep = requests.get(
         url,
         headers={'Authorization': 'Bearer ' + token},
         params={'title': request.query_params.get('search')})
     return Response(response_format(rep.json()))
示例#13
0
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = serializer.data

        rules = serializer.data['rules']
        data['subject'] = gourp_rules(rules)

        return Response(response_format(data))
示例#14
0
    def preview(self, request, pk, *args, **kwargs):
        exam_task = self.get_object()
        serializers = ExamTaskPaperPreviewSerializer(exam_task)
        data = serializers.data
        if exam_task.exampaper_create_type == 'fixed':
            problems = exam_task.problems.all()
            problems_serializer = ExamPaperProblemsSnapShotSerializer(
                problems, many=True)
            data['problems'] = problems_serializer.data

            return Response(response_format(data))

        elif exam_task.exampaper_create_type == 'random':
            rules = exam_task.rules.all()
            rules_serializer = ExamPaperCreateRuleSerializer(rules, many=True)
            data['subject'] = gourp_rules(rules_serializer.data)

            return Response(response_format(data))
示例#15
0
 def get(self, request, *args, **kwargs):
     USER_INFO_API = 'api/mobile/v0.5/my_user_info'
     token = request.user.social_auth.first().extra_data['access_token']
     url = settings.EDX_LMS_PATH + USER_INFO_API
     rep = requests.get(
         url,
         headers={'Authorization': 'Bearer ' + token},
     )
     return Response(response_format(rep.json()))
示例#16
0
 def get(self, request, *args, **kwargs):
     USERS_INFO_API = '/exam/users'
     token = request.user.social_auth.first().extra_data['access_token']
     url = settings.EDX_API['HOST'] + USERS_INFO_API
     rep = requests.get(
         url,
         headers={'Authorization': 'Bearer ' + token},
         params=request.GET,
     )
     return Response(response_format(rep.json()))
示例#17
0
    def partial_update(self, request, *args, **kwargs):
        """
        「考试中」和「考试结束」不可编辑
        """
        instance = self.get_object()
        if instance.task_state in (TASK_STATE[1][0], TASK_STATE[2][0]):
            return Response(response_format(msg='Can not edit started task'))

        return super(ExamTaskViewSet,
                     self).partial_update(request, args, kwargs)
示例#18
0
    def create(self, request, *args, **kwargs):
        request.data['creator'] = request.user.id

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(response_format(serializer.data),
                        status=status.HTTP_201_CREATED,
                        headers=headers)
示例#19
0
    def partial_update(self, request, *args, **kwargs):
        """
        更新部分
        """
        instance = self.get_object()
        instance.answer = str(request.data['answer'])
        instance.operate_at = datetime.datetime.now()
        instance.save()

        return Response(response_format(data=[], msg='作答成功'))
示例#20
0
    def post(self, request, *args, **kwargs):
        token = request.user.social_auth.first().extra_data['access_token']

        section_ids = request.data.get('section_ids')

        url = settings.EDX_API['HOST'] + settings.EDX_API[
            'SECTION_PROBLEM_TYPE_COUNT']
        rep = requests.post(url,
                            headers={'Authorization': 'Bearer ' + token},
                            json={'section_id': section_ids})
        return Response(response_format(rep.json()))
示例#21
0
    def get_paginated_response(self, data, **kwargs):
        result = [
            ('count', self.page.paginator.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data),
        ]

        if kwargs:
            result += kwargs.items()

        return Response(response_format(OrderedDict(result)))
示例#22
0
    def get(self, request, block_id, *args, **kwargs):

        token = request.user.social_auth.first().extra_data['access_token']
        url = settings.EDX_API['HOST'] + settings.EDX_API['COURSE_PROBLEMS']
        payload = {
            'block_id': block_id,
            'text': request.query_params.get('search', ''),
            'problem_type': request.query_params.get('problem_type', None),
            'page': request.query_params.get('page'),
            'page_size': request.query_params.get('page_size'),
        }
        rep = requests.get(url,
                           headers={'Authorization': 'Bearer ' + token},
                           params=payload)
        if rep.status_code == 400:
            return Response(
                response_format(status=rep.json().get('code'),
                                msg=rep.json().get('msg')))
        elif rep.status_code == 200:
            return Response(response_format(rep.json()))
        else:
            return Response(rep.text)
示例#23
0
 def create(self, request, *args, **kwargs):
     """
     提交试卷
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     participant_id = str(self.request.data['participant_id'])
     exam_participant = ExamParticipant.objects.filter(
         id=participant_id).first()
     if not exam_participant:
         return Response(response_format(data=[], msg='考试不存在', status=-1))
     if exam_participant.task_state == TASK_STATE[1][0]:
         problems = ExamParticipantAnswerSerializer(
             request.data['problems'])
         exam_participant_answers = ExamParticipantAnswer.objects.filter()
         total_grade = 0
         with transaction.atomic():
             for problem in problems.instance:
                 exam_participant_answer = exam_participant_answers.filter(
                     id=str(problem['id'])).first()
                 if exam_participant_answer:
                     exam_participant_answer.answer = str(problem['answer'])
                     # 计算分数
                     exam_participant_answer.grade = self.calculating_score(
                         exam_participant_answer)
                     total_grade += exam_participant_answer.grade
                     exam_participant_answer.save()
             exam_participant.task_state = TASK_STATE[2][0]
             exam_participant.exam_result = self.get_exam_reuslt(
                 exam_participant, total_grade)
             exam_participant.save()
     else:
         return Response(response_format(data=[], msg='只有考试中的试卷允许提交'))
     return Response(response_format(data=[], msg='提交成功'))
示例#24
0
    def create(self, request, *args, **kwargs):
        request.data['creator'] = request.user.id

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        tasks.start_exam_task.apply_async(
            [serializer.data.get('id')],
            eta=serializer.data.get('period_start'))

        return Response(response_format(serializer.data),
                        status=status.HTTP_201_CREATED,
                        headers=headers)
示例#25
0
    def get_return_response(self, data, **kwargs):
        """
        自定义格式化返回
        :param data:
        :param kwargs:
        :return:
        """
        result = [
            ('results', data),
        ]

        if kwargs:
            result += kwargs.items()

        return Response(response_format(OrderedDict(result)))
示例#26
0
def custom_exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.

    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}

        set_rollback()
        print 'something happen'
        return Response(response_format(status=-1, msg=exc.detail),
                        status=exc.status_code,
                        headers=headers)

    elif isinstance(exc, Http404):

        msg = _('Not found.')
        data = {'detail': six.text_type(msg)}

        set_rollback()
        return Response(data, status=status.HTTP_404_NOT_FOUND)

    elif isinstance(exc, PermissionDenied):
        msg = _('Permission denied.')
        data = {'detail': six.text_type(msg)}

        set_rollback()
        return Response(data, status=status.HTTP_403_FORBIDDEN)

    # Note: Unhandled exceptions will raise a 500 error.
    logging.exception(exc)

    return None
示例#27
0
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)

        request.data['create_type'] = PAPER_CREATE_TYPE[1][0]
        request.data['creator'] = request.user.id

        rules = request.data['subject']
        new_rules = []
        for rule in rules:
            new_rules += [
                {
                    'problem_section_id': rule['id'],
                    'section_name': rule['name'],
                    'problem_type': 'choiceresponse',
                    'problem_num': rule['choiceresponseNumber'],
                    'grade': rule['choiceresponseGrade']
                },
                {
                    'problem_section_id': rule['id'],
                    'section_name': rule['name'],
                    'problem_type': 'multiplechoiceresponse',
                    'problem_num': rule['multiplechoiceresponseNumber'],
                    'grade': rule['multiplechoiceresponseGrade']
                },
                {
                    'problem_section_id': rule['id'],
                    'section_name': rule['name'],
                    'problem_type': 'stringresponse',
                    'problem_num': rule['stringresponseNumber'],
                    'grade': rule['stringresponseGrade']
                },
            ]
        request.data['rules'] = new_rules

        instance = self.get_object()
        serializer = self.get_serializer(instance,
                                         data=request.data,
                                         partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(response_format(serializer.data))
示例#28
0
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)

        request.data['create_type'] = PAPER_CREATE_TYPE[0][0]
        request.data['creator'] = request.user.id

        instance = self.get_object()
        serializer = self.get_serializer(instance,
                                         data=request.data,
                                         partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(response_format(serializer.data))
示例#29
0
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        rules = serializer.data['rules']

        data = serializer.data

        subject = []
        for name, group in groupby(rules, lambda x: x['section_name']):
            section_rule = {
                'name': name,
            }
            for rule in group:
                section_rule['id'] = rule['problem_section_id']
                section_rule[rule['problem_type'] + 'Grade'] = rule['grade']
                section_rule[rule['problem_type'] +
                             'Number'] = rule['problem_num']
            subject.append(section_rule)
        data['subject'] = subject

        return Response(response_format(data))
示例#30
0
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        state_queryset = ExamTask.objects.filter(creator=request.user)
        state_count = {
            'pending': state_queryset.filter(task_state='pending').count(),
            'started': state_queryset.filter(task_state='started').count(),
            'finished': state_queryset.filter(task_state='finished').count(),
        }

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = ExamTaskListSerializer(page, many=True)
            assert self.paginator is not None
            return self.paginator.get_paginated_response(
                serializer.data, **state_count)

        serializer = ExamTaskListSerializer(queryset, many=True)
        rep_data = {'exam_tasks': serializer.data}
        rep_data.update(state_count)
        return Response(response_format(rep_data))