Esempio n. 1
0
def courses_list(request):
    """
    List all courses, or create a new course.
    """
    if request.method == 'GET':
        user_id = request.user.user_id
        if request.user.character in [2, 3]:
            teaches_objects = Teach.objects.filter(teacher_id=user_id)
            teaches_list = TeachSerializers(teaches_objects, many=True).data
            course_list = []
            for teach in teaches_list:
                course = CourseSerializers(Course.objects.get(course_id=teach['course_id'])).data
                course_list.append(course)
        elif request.user.character == 1:
            course_list = CourseSerializers(Course.objects.all(), many=True).data
        else:
            # for student
            takes_list = TakeCourseSerializer(TakeCourse.objects.filter(student_id=user_id), many=True).data
            course_list = []
            for take in takes_list:
                course = CourseSerializers(Course.objects.get(course_id=take['course_id'])).data
                course_list.append(course)
        return Response(generate_response(course_list, True))

    elif request.method == 'POST':
        serializer = CourseSerializers(data=request.data)
        if request.user.character in [2, 3, 4]:
            response_data = {"error_msg": 'permission denied'}
            return Response(utils.generate_response(response_data, False), status=status.HTTP_400_BAD_REQUEST)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 2
0
def is_student_within_course(student_id, course_id) -> bool:
    takes = TakeCourse.objects.filter(student_id=student_id)
    takes_serializer = TakeCourseSerializer(takes, many=True)
    course_id_list = []
    for take in takes_serializer.data:
        course_id_list.append(take['course_id'])
    if course_id not in course_id_list:
        return False
    return True
Esempio n. 3
0
def get_students_by_course_id(request, course_id):
    """
    List all courses, or create a new course.
    """
    if request.method == 'GET':

        # check params
        params = request.query_params.dict()
        pg_num = params.get('pageNum', None)
        pg_size = params.get('pageSize', None)
        is_valid, error_response = utils.page_params_check(pg_num, pg_size)
        if not is_valid:
            return Response(utils.generate_response(error_response, False),
                            status=status.HTTP_400_BAD_REQUEST)
        pg_num, pg_size = int(pg_num), int(pg_size)

        if request.user.character in [2, 3]:
            teacher_id = request.user.user_id
            teaches = Teach.objects.filter(teacher_id=teacher_id)
            teaches_serializer = TeachSerializers(teaches, many=True)
            course_id_list = []
            for teach in teaches_serializer.data:
                course_id_list.append(teach['course_id'])
            if course_id not in course_id_list:
                response_data = {
                    "error_msg":
                    'permission denied, You have not yet bound the corresponding course'
                }
                return Response(utils.generate_response(response_data, False),
                                status=status.HTTP_400_BAD_REQUEST)
        take_objects = TakeCourse.objects.filter(course_id=course_id)
        take_list = TakeCourseSerializer(take_objects, many=True).data
        student_list = []
        for take in take_list:
            student_object = User.objects.get(user_id=take['student_id'])
            student_list.append(utils.my_user_serializer(student_object))
        sorted(student_list, key=lambda x: x['user_id'])
        pg_end = min(pg_num * pg_size, len(student_list))
        pg_start = (pg_num - 1) * pg_size
        if pg_start < len(student_list):
            response_student_list = student_list[pg_start:pg_end]
        else:
            response_student_list = []
        ans = {
            'students': response_student_list,
            'pagination': {
                'pageNum': pg_num,
                'pageSize': pg_size,
                'total': len(student_list)
            }
        }
        return Response(ans)
Esempio n. 4
0
def get_course_case_statistics(request, course_case_id):
    course_case = CourseCase.objects.get(course_case_id=course_case_id)
    course_id = CourseCaseSerializer(course_case).data['course_id']
    print(course_id)
    takes = TakeCourseSerializer(
        TakeCourse.objects.all().filter(course_id=course_id), many=True).data
    # 选课人数
    user_id_list = [take['student_id'] for take in takes]
    print(user_id_list)
    # 提交人数
    assignment_list = ExperimentAssignmentSerializer(
        ExperimentAssignment.objects.all().filter(
            course_case_id=course_case_id),
        many=True).data
    submission_num = len(assignment_list)
    print(submission_num)
    # 已批改的人数
    remarked_list = [
        assignment for assignment in assignment_list
        if assignment['submission_score'] > 0
    ]
    remarked_num = len(remarked_list)
    # 分数段 0-60 61-70 71-80 81-90 91-100
    score_distributed = [0, 0, 0, 0, 0]
    for remarked in remarked_list:
        if remarked['submission_score'] <= 60:
            score_distributed[0] += 1
        elif remarked['submission_score'] <= 70:
            score_distributed[1] += 1
        elif remarked['submission_score'] <= 80:
            score_distributed[2] += 1
        elif remarked['submission_score'] <= 90:
            score_distributed[3] += 1
        elif remarked['submission_score'] <= 100:
            score_distributed[4] += 1
    answer = {
        'submitted_num': submission_num,
        'unsubmitted_num': len(user_id_list) - submission_num,
        'remarked_num': remarked_num,
        'unremarked_num': submission_num - remarked_num,
        'score_distributed': score_distributed,
    }
    return Response(utils.generate_response(answer, True))
Esempio n. 5
0
def take_list(request):
    if request.method == 'GET':
        take_list = TakeCourse.objects.all()
        serializer = TakeCourseSerializer(take_list, many=True)
        answer = serializer.data
        for index, take in enumerate(answer):
            course_id = take['course_id']
            course_info = CourseSerializers(
                Course.objects.get(course_id=course_id)).data
            answer[index]['course_name'] = course_info['course_name']
            answer[index]['course_description'] = course_info[
                'course_description']
            answer[index]['course_credit'] = course_info['course_credit']
            user_id = take['student_id']
            student = User.objects.get(pk=user_id)
            answer[index]['email'] = student.email
            answer[index]['realname'] = student.realname
            answer[index]['student_user_id'] = answer[index]['student_id']
            answer[index]['student_id'] = student.personal_id
        return Response(generate_response(serializer.data, True))
Esempio n. 6
0
def assignment_student_list(request):
    """
    List all assignments for a particular student.
    Submit a assignment
    """
    if request.method == 'GET':
        assignments = ExperimentAssignment.objects.filter(
            submission_uploader=request.user.user_id)
        # assignments = assignments.filter()
        serializer = ExperimentAssignmentSerializer(assignments, many=True)
        return Response(
            utils.generate_response(
                utils.student_assignments_filter(serializer.data), True))

    elif request.method == 'POST':
        # 输入字段检测
        if not utils.is_submission_valid(request.data):
            return Response(utils.generate_response({"error_msg": '参数错误'},
                                                    False),
                            status=status.HTTP_400_BAD_REQUEST)

        # 获取学生选过的课程集合
        user_id = request.user.user_id
        course_objects = TakeCourse.objects.filter(student_id=user_id)
        course_id_list = []
        tmp_serializer = TakeCourseSerializer(course_objects, many=True)

        for item in tmp_serializer.data:
            course_id_list.append(item['course_id'])
        course_id_set = set(course_id_list)

        # 检测上传的课程是否是在选过的课程中
        course_id = request.data['course_id']
        if course_id not in course_id_set:
            error_res = {"error_msg": '提交的课程尚未加入'}
            return Response(utils.generate_response(error_res, False),
                            status=status.HTTP_400_BAD_REQUEST)
        print('wzj')
        try:
            course_case_object = CourseCase.objects.get(
                pk=request.data['course_case_id'])
        except CourseCase.DoesNotExist:
            error_data = {"detail": "course case not exist"}
            return Response(utils.generate_response(error_data, False),
                            status=status.HTTP_404_NOT_FOUND)

        course_case = CourseCaseSerializer(course_case_object).data

        # DDL检验
        if not utils.check_ddl(course_case['case_end_timestamp']):
            return Response(
                utils.generate_response({"error_msg": 'Assignment is due'},
                                        False))

        request.data['submission_uploader'] = user_id

        # upload url
        response_headers = {}
        file_display_name = request.data["submission_file_name"]
        random_hex_string = ('%030x' % random.randrange(16**30))
        file_token = f"{EXPERIMENT_CASE_PREFIX}/{random_hex_string}/{file_display_name}"
        post_url = local_minio_client.presigned_url(
            "PUT",
            DEFAULT_BUCKET,
            file_token,
            expires=DEFAULT_FILE_URL_TIMEOUT)
        request.data['submission_file_token'] = file_token
        response_headers['SUBMISSION_UPLOAD_URL'] = post_url

        serializer = ExperimentAssignmentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(utils.generate_response(serializer.data, True),
                            headers=response_headers,
                            status=status.HTTP_201_CREATED)
        return Response(utils.generate_response(serializer.errors, False),
                        status=status.HTTP_400_BAD_REQUEST)
Esempio n. 7
0
def upload(request):
    if request.method == "POST":
        # 检查是否存在文件表单
        try:
            excel_file = request.FILES['student-course-list-file']
        except Exception as e:
            print('in exception error is:', str(e))
            return Response(
                {
                    'is_success': False,
                    'msg': 'your form data lost key:' + str(e)
                },
                status=status.HTTP_400_BAD_REQUEST)
        rd = str(int(random.random() * 1e6))
        tmp_file_name = rd + 'student-course-list.xlsx'
        response_msg = []

        # 是否成功导入
        try:
            # 读取数据到data frame
            with open(tmp_file_name, 'wb') as destination:
                for chunk in excel_file.chunks():
                    destination.write(chunk)
            df = pd.read_excel(tmp_file_name, engine='openpyxl')
            keys = df.keys()
            # 文件列名检查
            # 此处student_id是学号
            print(set(keys))
            if set(keys) == {'student_id', 'course_id'}:
                # 遍历检查合法性
                for index, row in df.iterrows():
                    row_dict = dict(row)
                    email = str(row_dict['student_id']) + '@tongji.edu.cn'
                    course_id = row_dict['course_id']
                    student = User.objects.filter(email=email)
                    # 检查学生
                    if len(student) == 0:
                        return Response(
                            {
                                'is_success': False,
                                'msg': 'student:' + email + ' not exists'
                            },
                            status=status.HTTP_400_BAD_REQUEST)
                    # 检查课程
                    try:
                        course = Course.objects.get(pk=course_id)
                    except Exception as e:
                        print(str(e))
                        return Response(
                            {
                                'is_success': False,
                                'msg':
                                'course:' + str(course_id) + ' not exists'
                            },
                            status=status.HTTP_400_BAD_REQUEST)
                    # 检查选课
                    try:
                        takeCourseItem = TakeCourse.objects.get(
                            student_id=student[0].user_id, course_id=course)
                        return Response(
                            {
                                'is_success':
                                False,
                                'msg':
                                email + 'take course:' + str(course_id) +
                                'exists'
                            },
                            status=status.HTTP_400_BAD_REQUEST)
                    except Exception as e:
                        pass
                # 遍历并且导入
                for index, row in df.iterrows():
                    row_dict = dict(row)
                    email = str(row_dict['student_id']) + '@tongji.edu.cn'
                    course_id = row_dict['course_id']
                    student = User.objects.filter(email=email)
                    user_id = student[0].user_id
                    serializer = TakeCourseSerializer(data={
                        'course_id': course_id,
                        'student_id': user_id
                    })
                    if serializer.is_valid():
                        serializer.save()
                return Response({'is_success': True},
                                status=status.HTTP_201_CREATED)

            elif set(keys) == {'email', 'course_id'}:
                # FIXME: 支持email导入
                e = 'in exception, error is: columns name is not: student_id, course_id or email, course_id'
                print(e)
                return Response({
                    'is_success': False,
                    'msg': str(e)
                },
                                status=status.HTTP_400_BAD_REQUEST)
            else:
                e = 'in exception, error is: columns name is not: student_id, course_id or email, course_id'
                print(e)
                return Response({
                    'is_success': False,
                    'msg': str(e)
                },
                                status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            print(str(e))
            is_success = False
            return Response({
                'is_success': False,
                'msg': response_msg
            },
                            status=status.HTTP_400_BAD_REQUEST)
        finally:
            os.remove(tmp_file_name)