import os import tempfile from django.forms import ValidationError from rest_framework import serializers from users.models import CustomUser from users.serializers import UserSerializer from .models import Exercice, Tag from api.Generateur import Generateur import importlib.util from .utils import checkExoModelObject class ExerciceSerializer(serializers.ModelSerializer): tags = serializers.SerializerMethodField() author = serializers.SerializerMethodField() origin = serializers.SerializerMethodField() isUser = serializers.SerializerMethodField() class Meta: model = Exercice fields = ('name', 'id_code', 'consigne', 'author', 'exemple', 'tags', 'isPdf', 'isCsv', 'isWeb', "private", 'tags', 'origin', 'isUser', 'last_update') def get_author(self, obj): return UserSerializer(obj.author).data ''' def get_exo_model(self,obj): pass ''' def get_isUser(self, obj): try: user = CustomUser.objects.filter( id_code=self.context['user_id'])[0] return obj.author == user except: return False def get_tags(self, obj): try: user = CustomUser.objects.filter( id_code=self.context['user_id'])[0] return [{**TagSerializer(t).data, 'value': t.id_code, 'label': t.name} for t in obj.tags.all() if t.user == user] except: return [] def get_origin(self,obj): return obj.origin if obj.origin == None else {'id_code': obj.origin.id_code} class ExerciceCreateSerializer(serializers.ModelSerializer): class Meta: model = Exercice fields = ('name', 'consigne', 'exo_model', 'private') def validate_exo_model(self, value): with tempfile.TemporaryDirectory() as d: with open(os.path.join(d, 'tmp.py'), 'w') as f: data = value.read().decode('utf8') f.write(data) spec = importlib.util.spec_from_file_location( "tmp", os.path.join(d, 'tmp.py')) tmp = importlib.util.module_from_spec(spec) spec.loader.exec_module(tmp) try: main_func = tmp.main except AttributeError: raise serializers.ValidationError( 'Manque main', code='invalid') main_result = main_func() default_object = {"calcul": False, 'pdf': False, 'csv': False, 'web': False, 'correction': False} # les valeurs par défaut # Si l'utilisateur n'a pas entré une valeur, elle est définie à False result_object = {**default_object, **main_result} exoCategory = checkExoModelObject(result_object) if not exoCategory['isPdf'] and not exoCategory['isCsv'] and not exoCategory['isWeb']: raise serializers.ValidationError( 'object invalid', code='invalid') return { **exoCategory, 'file': value } def create(self, validated_data, **kwargs): exo_model = validated_data.pop('exo_model') return Exercice.objects.create(**validated_data) class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('id', 'name', 'color', 'id_code')