示例#1
0
class ArticleSerializer(OwnerFieldSerializer):
    status = ChoiceField(choices=Article.STATUS_CHOICES, required=False)
    arttype = ChoiceField(choices=Article.ARTTYPE, required=False)
    comment_status = ChoiceField(choices=Article.COMMENT_STATUS,
                                 required=False)
    thumbnail = serializers.ImageField(read_only=True)

    class Meta:
        model = Article
        fields = '__all__'
        read_only_fields = ('id', 'modified', 'created', 'views', 'creater',
                            'thumbnail')
        ordering = ['pub_time', 'modified']
        extra_kwargs = {'description': {'required': False}}
示例#2
0
class NotificationTaskCreateSerializer(serializers.ModelSerializer):
    actor = serializers.HiddenField(default=serializers.CurrentUserDefault())
    # actor = GenericNotificationRelatedField(read_only=True)
    action = GenericNotificationRelatedField(read_only=True)
    target = GenericNotificationRelatedField(read_only=True)
    status = ChoiceField(choices=NotificationTask.STATUS_CHOICES,
                         required=False)

    class Meta:
        model = NotificationTask
        fields = ('id', 'level', 'reason', 'actor', 'verb', 'description',
                  'target', 'action', 'public', 'data', 'users', 'departments',
                  'groups', 'status')
        read_only_fields = (
            'id',
            'actor',
            'target',
            'action',
        )
        ordering = ['created']
        extra_kwargs = {
            'groups': {
                'write_only': True
            },
            'departments': {
                'write_only': True
            },
            'users': {
                'write_only': True
            }
        }
示例#3
0
class PublicLearnProgressReadonlySerializer(serializers.ModelSerializer):
    status = ChoiceField(choices=PublicLearnProgress.STATUS_CHOICES)
    course = CoursewareSerializer(read_only=True)
    rate_progress = serializers.SerializerMethodField()

    class Meta:
        model = PublicLearnProgress
        fields = [
            'id', 'status', 'start_time', 'end_time', 'progress',
            'rate_progress', 'course'
        ]
        read_only_fields = ('id', 'status', 'start_time', 'end_time',
                            'progress', 'rate_progress', 'course')
        ordering = ['created']
        # expandable_fields = {'course': (
        #     CoursewareSerializer, {'source': 'course', 'read_only': True})}

    def get_rate_progress(self, learnprogress):
        property = learnprogress.course.property

        if learnprogress.course.file_type == 'PDF':
            numpage = learnprogress.progress['numpage']
            return round(100 * numpage / property['numpages'])

        if learnprogress.course.file_type == 'MP4':
            starttime = learnprogress.progress.get('starttime', 0)
            return round(100 * starttime / property['duration'])
示例#4
0
class LearnProgressSerializer(serializers.ModelSerializer):
    # course = CoursewareSerializer(source='plan.course')
    plan = LearnPlanReadonlySerializer()
    status = ChoiceField(choices=LearnProgress.STATUS_CHOICES)

    class Meta:
        model = LearnProgress
        fields = '__all__'
        read_only_fields = ('plan', 'type', 'create_time', 'trainer', 'course',
                            'plan')
        ordering = ['create_time']

    def to_internal_value(self, data):
        if self.instance.status == 'completed' or self.instance.status == 'overdueCompleted':
            data.pop('status', None)
        if self.instance.status == 'learning':
            status = data.get('status', 'learning')
            if status == 'completed' or status == 'overdueCompleted':
                data['end_time'] = timezone.now()
                if data['end_time'] > self.instance.plan.end_time:
                    data['status'] = 'overdueCompleted'
        ret = super(LearnProgressSerializer, self).to_internal_value(data)
        # 修改修改学习计划的状态

        return ret
示例#5
0
class CoursewareModifySerializer(serializers.ModelSerializer):
    serializer_choice_field = ChoiceField
    category = ChoiceField(choices=Courseware.COURSEWARE_CATEGORY_CHOICES)
    file_type = ChoiceField(choices=Courseware.FILE_TYPE_CHOICES)
    status = ChoiceField(choices=Courseware.STATUS_CHOICES)

    class Meta:
        model = Courseware
        fields = [
            "id", "name", "category", "departments", "intruduce",
            "applicable_user", "class_hour", "file_type", "teachername",
            "teacherdesc", 'teacherimg', "cover", "status", "drag_flag",
            'create_time', 'courseware_file', "property", "recommend"
        ]
        read_only_fields = ('id', 'cover', 'create_time', 'teacherimg',
                            'courseware_file', "property")

        ordering = ['create_time'],
示例#6
0
class PublicLearnProgressSerializer(OwnerFieldSerializer):
    status = ChoiceField(required=False,
                         choices=PublicLearnProgress.STATUS_CHOICES)

    class Meta:
        model = PublicLearnProgress
        fields = [
            'id', 'status', 'start_time', 'end_time', 'progress', 'course',
            "creater"
        ]
        read_only_fields = ('type', 'created', 'start_time')
        ordering = ['created']
示例#7
0
class ExamProgressByGroupSerializer(serializers.ModelSerializer):
    trainer_name = serializers.CharField(source='trainer.name')
    trainer_no = serializers.CharField(source='trainer.user_no')
    trainer_department = serializers.CharField(
        source='trainer.department.name')
    status = ChoiceField(choices=ExamProgress.STATUS_CHOICES)

    class Meta:
        model = ExamProgress
        fields = ['trainer_name', 'trainer_no', 'trainer_department', 'status']
        read_only_fields = ('trainer_name', 'trainer_no', 'trainer_department',
                            'status')
        ordering = ['created']

    def to_internal_value(self):
        super(ExamProgressByGroupSerializer, self).to_internal_value()
示例#8
0
class ExamPlanSerializer(OwnerFlexFSerializer):
    department = serializers.HiddenField(
        default=CurrentUserDepartmentDefault())
    status = ChoiceField(required=False, choices=ExamPlan.STATUS_CHOICES)
    ratio = serializers.SerializerMethodField()

    class Meta:
        model = ExamPlan
        fields = [
            'id', 'name', 'start_time', 'exampaper', 'department', 'creater',
            'end_time', 'traingroups', 'status', 'ratio'
        ]
        read_only_fields = ('id', 'created', 'creater', 'status', 'ratio')
        ordering = ['created']
        extra_kwargs = {
            'traingroups': {
                'write_only': True
            },
            'course': {
                'write_only': True
            }
        }
        expandable_fields = {'exampaper': ExamPaPerSerializer}

    def get_ratio(self, examplan):
        num_completed = examplan.progresses.filter(status='completed').count()
        count = examplan.progresses.count()
        return '{}/{}'.format(num_completed, count)

    def create(self, validated_data):
        traingroups = validated_data['traingroups']
        instance = super(ExamPlanSerializer, self).create(validated_data)
        quesitons = instance.exampaper.get_quesitons()
        for traingroup in traingroups:
            trainers = traingroup.get_trainers()
            if trainers:
                for trainer in trainers:
                    # 添加 answers
                    answers = instance.exampaper.get_quesitons()
                    answerlist = list(answers)
                    for value in answerlist:
                        value.update(answer='')
                    trainer.examplan_progresses.create(plan=instance,
                                                       answers=answerlist)
        return instance
示例#9
0
class ExamProgressModifySerializer(OwnerFieldSerializer):

    status = ChoiceField(choices=ExamProgress.STATUS_CHOICES)

    class Meta:
        model = ExamProgress
        fields = ['id', 'answers', 'score', 'status']
        read_only_fields = ['status']

    def to_internal_value(self, data):
        if self.instance.status == 'completed' or self.instance.status == 'overdueCompleted':
            data.pop('status', None)
        if self.instance.status == 'examing':
            status = data.get('status', 'examing')
            if status == 'completed' or status == 'overdueCompleted':
                data['end_time'] = timezone.now()
                if data['end_time'] > self.instance.plan.end_time:
                    data['status'] = 'overdueCompleted'
        cerect_answer = self.instance.plan.exampaper.questions.all().values(
            'id', 'answer', 'score')
        answers = data.get('answers', None)
        cerect_answerdict = {}
        score = 0
        for item in cerect_answer:
            id = item['id']
            cerect_answerdict.update(
                {id: {
                    'answer': item['answer'],
                    'score': item['score']
                }})
        for answer in answers:
            id = answer['id']

            if answer['answer'] == cerect_answerdict[id]['answer']:
                score += cerect_answerdict[id]['score']
        if self.instance.score >= score:
            data.pop('answers', None)
        else:
            data.update(score=score)

        ret = super(ExamProgressModifySerializer, self).to_internal_value(data)
        # 修改考试的状态

        return ret
示例#10
0
class NotificationListTaskSerializer(FlexFieldsModelSerializer):
    # actor = serializers.HiddenField(default=serializers.CurrentUserDefault())
    actor = GenericNotificationRelatedField(read_only=True)
    action = GenericNotificationRelatedField(read_only=True)
    target = GenericNotificationRelatedField(read_only=True)
    status = ChoiceField(choices=NotificationTask.STATUS_CHOICES,
                         required=False)

    class Meta:
        model = NotificationTask
        fields = ('id', 'level', 'reason', 'actor', 'verb', 'description',
                  'target', 'action', 'public', 'data', 'status')
        read_only_fields = (
            'id',
            'actor',
            'target',
            'action',
        )
        ordering = ['created']
示例#11
0
class ExamProgressSerializer(OwnerFlexFSerializer):

    status = ChoiceField(choices=ExamProgress.STATUS_CHOICES)
    days_remaining = serializers.SerializerMethodField()

    class Meta:
        model = ExamProgress
        fields = [
            'id', 'created', 'trainer', 'plan', 'status', 'start_time',
            'end_time', 'score', 'answers', 'days_remaining'
        ]
        read_only_fields = ('id', 'created', 'trainer', 'plan', 'score',
                            'days_remaining')
        ordering = ['created']
        expandable_fields = {'plan': ExamPlanReadonlySerializer}

    def get_days_remaining(self, examprogress):
        today = pendulum.today().date()
        period = pendulum.period(today,
                                 examprogress.plan.end_time.date(),
                                 absolute=False)
        return period.days if period.days > 0 else 0
示例#12
0
class ExamProgressOnlySerializer(serializers.ModelSerializer):
    plan = ExamPlanReadonlySerializer()
    status = ChoiceField(choices=ExamProgress.STATUS_CHOICES)
    days_remaining = serializers.SerializerMethodField()

    class Meta:
        model = ExamProgress
        fields = [
            'id', 'created', 'trainer', 'plan', 'status', 'start_time',
            'end_time', 'score', 'answers', 'days_remaining'
        ]
        read_only_fields = [
            'id', 'created', 'trainer', 'plan', 'status', 'start_time',
            'score', 'answers', 'days_remaining'
        ]
        ordering = ['created']

    def get_days_remaining(self, examprogress):
        today = pendulum.today().date()
        period = pendulum.period(examprogress.plan.end_time.date(),
                                 today,
                                 absolute=True)
        return period.days
示例#13
0
class LearnPlanSerializer(OwnerFieldSerializer):
    department = serializers.HiddenField(
        default=CurrentUserDepartmentDefault())
    # traingroups = serializers.PrimaryKeyRelatedField(required=True, many=True, queryset=TrainGroup.objects.all())
    # creater = serializers.HiddenField(
    #     default=serializers.CurrentUserDefault()
    # )
    status = ChoiceField(required=False, choices=LearnPlan.STATUS_CHOICES)
    course_name = serializers.CharField(source='course.name', read_only=True)

    class Meta:
        model = LearnPlan
        fields = [
            'id', 'name', 'start_time', 'course', 'course_name', 'department',
            'creater', 'end_time', 'orexame', 'traingroups', 'status'
        ]
        read_only_fields = ('id', 'create_time', 'creater', 'course_name',
                            'status')
        ordering = ['create_time']
        extra_kwargs = {
            'traingroups': {
                'write_only': True
            },
            'course': {
                'write_only': True
            }
        }

    def create(self, validated_data):
        traingroups = validated_data['traingroups']
        instance = super(LearnPlanSerializer, self).create(validated_data)
        for traingroup in traingroups:
            trainers = traingroup.get_trainers()
            if trainers:
                for trainer in trainers:
                    trainer.learnplan_progresses.create(plan=instance)
        return instance
示例#14
0
class CoursewareCreateSerializer(serializers.ModelSerializer):
    serializer_choice_field = ChoiceField
    zipfileid = serializers.IntegerField(write_only=True)
    User = get_user_model()
    # trainmanagers = serializers.PrimaryKeyRelatedField(
    #     write_only=True, required=False, many=True, queryset=User.objects.all())
    # departments = serializers.PrimaryKeyRelatedField(
    #     required=False, many=True, queryset=Department.objects.all())
    category = ChoiceField(choices=Courseware.COURSEWARE_CATEGORY_CHOICES)
    file_type = ChoiceField(choices=Courseware.FILE_TYPE_CHOICES)
    status = ChoiceField(choices=Courseware.STATUS_CHOICES)
    # courseware_type = serializers.CharField(source='courseware_type.type')
    creater = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = Courseware
        fields = [
            'id', 'zipfileid', "departments", "courseware_no", "name",
            "category", "intruduce", "applicable_user", "class_hour",
            "file_type", "teachername", "teacherdesc", 'teacherimg', "cover",
            "status", "drag_flag", 'courseware_file', "type", "property",
            "create_time", 'creater', 'recommend'
        ]
        read_only_fields = [
            'id', 'create_time', "cover", 'cover', 'teacherimg',
            'courseware_file', "property", 'creater'
        ]

        ordering = ['create_time'],
        extra_kwargs = {
            # 'trainmanagers': {'write_only': True},
            # 'departments': {'write_only': True},
            'zipfileid': {
                'write_only': True
            }
        }

    def to_internal_value(self, data):
        # type = data.get('courseware_type', None)
        # courstype = Coursetype.objects.get(type=type)
        # data['courseware_type'] = courstype.type
        return super(CoursewareCreateSerializer, self).to_internal_value(data)

    # def validate_courseware_no(self, value):
    #     return value

    def validate(self, attrs):
        zipfileid = attrs['zipfileid']
        courseware_no = attrs['courseware_no']

        cover, teacherimg, courseware_file, config_dict, zipfile, file_type = self.unzipfile(
            zipfileid)
        if file_type != attrs['file_type']:
            raise serializers.ValidationError('上传文件与配置文件不一致')
        try:
            if file_type == 'MP4':
                movie = mp.VideoFileClip(courseware_file)

                attrs['property'] = {'duration': movie.duration}
                movie.close()
            if file_type == 'PDF':
                with open(courseware_file, "rb") as f:
                    pdf = PdfFileReader(f)
                    numpages = pdf.getNumPages()
                attrs['property'] = {'numpages': numpages}
        except Exception as e:
            raise serializers.ValidationError('解析上传文件错误')
        attrs['cover'] = File(open(cover, mode='rb'))
        attrs['cover'].name = '_'.join(
            [courseware_no, os.path.basename(cover)])
        attrs['teacherimg'] = File(open(teacherimg, mode='rb'))
        attrs['teacherimg'].name = '_'.join(
            [courseware_no, os.path.basename(teacherimg)])
        attrs['zipfile'] = File(open(zipfile, mode='rb'))
        attrs['zipfile'].name = '_'.join(
            [courseware_no, os.path.basename(zipfile)])
        attrs['courseware_file'] = File(open(courseware_file, mode='rb'))
        attrs['courseware_file'].name = '_'.join(
            [courseware_no, os.path.basename(courseware_file)])
        attrs['config_ini'] = config_dict
        del attrs['zipfileid']

        return attrs

    def unzipfile(self, zipfileid):
        """
        解压文件返回文件路径
        :return:

        """
        zipfileobject = Zipfile.objects.get(
            id=zipfileid)  # 查询数据库找到ID=1的zipfile
        if zipfileobject is None:
            return None

        unziparchive = unzipfile.ZipFile(zipfileobject.zipfile.path,
                                         'r')  # 拼接路径得到所需解压文件绝对路径
        # tempdir = os.path.join(['./',zipfileobject.zipfile.name[:-4]])
        # a=os.path.basename(zipfileobject.zipfile.path)
        curdir = os.path.dirname(zipfileobject.zipfile.path)
        mkdirname = os.path.splitext(zipfileobject.zipfile.path)[0]
        unzipdir = os.path.join(curdir, mkdirname)
        # 补充检查文件名是否规范
        file_list = unziparchive.namelist()
        if "fhlhg.jpg" in file_list:
            cover = unziparchive.extract("fhlhg.jpg", unzipdir)

        if "fb.jpg" in file_list:
            teacherimg = unziparchive.extract("fb.jpg", unzipdir)
        if "fhlhg.mp4" in file_list:
            courseware_file = unziparchive.extract("fhlhg.mp4", unzipdir)
            file_type = 'MP4'
        if "fhlhg.pdf" in file_list:
            courseware_file = unziparchive.extract("fhlhg.pdf", unzipdir)
            file_type = 'PDF'
        if "config.ini" in file_list:
            config_ini = unziparchive.extract("config.ini", unzipdir)
            # config_dir = os.path._getfullpathname(config_ini)

            conf = configparser.ConfigParser()
            conf.read(config_ini, encoding='utf-8')  # 读取ini文件

            config_dict = dict(conf._sections)  # 转换为字典 格式 需要提取数据转换
            # print(dic_con)
            # config_json = json.dumps(config_dic)

        unziparchive.close()
        return cover, teacherimg, courseware_file, config_dict, zipfileobject.zipfile.path, file_type