Ejemplo n.º 1
0
class ResponseSerializer(serializers.Serializer):
    document = DictField(child=StatisticsSerializer())
Ejemplo n.º 2
0
 def validate_update_list(self, data):
     DictField().run_validation(data)
     pks = list(data.keys())
     self.validate_pk_list(pks)
     values = list(data.values())
     self.validate_data_list(values)
Ejemplo n.º 3
0
class UserSelfSerializer(ModelSerializer):
    """User Serializer for information a user can retrieve about themselves and
    update about themselves"""

    is_superuser = BooleanField(read_only=True)
    avatar = CharField(read_only=True)
    groups = SerializerMethodField()
    uid = CharField(read_only=True)
    settings = DictField(source="attributes.settings", default=dict)

    @extend_schema_field(
        ListSerializer(child=inline_serializer(
            "UserSelfGroups",
            {
                "name": CharField(read_only=True),
                "pk": CharField(read_only=True)
            },
        )))
    def get_groups(self, _: User):
        """Return only the group names a user is member of"""
        for group in self.instance.ak_groups.all():
            yield {
                "name": group.name,
                "pk": group.pk,
            }

    def validate_email(self, email: str):
        """Check if the user is allowed to change their email"""
        if self.instance.group_attributes().get(
                USER_ATTRIBUTE_CHANGE_EMAIL,
                CONFIG.y_bool("default_user_change_email", True)):
            return email
        if email != self.instance.email:
            raise ValidationError("Not allowed to change email.")
        return email

    def validate_name(self, name: str):
        """Check if the user is allowed to change their name"""
        if self.instance.group_attributes().get(
                USER_ATTRIBUTE_CHANGE_NAME,
                CONFIG.y_bool("default_user_change_name", True)):
            return name
        if name != self.instance.name:
            raise ValidationError("Not allowed to change name.")
        return name

    def validate_username(self, username: str):
        """Check if the user is allowed to change their username"""
        if self.instance.group_attributes().get(
                USER_ATTRIBUTE_CHANGE_USERNAME,
                CONFIG.y_bool("default_user_change_username", True)):
            return username
        if username != self.instance.username:
            raise ValidationError("Not allowed to change username.")
        return username

    def save(self, **kwargs):
        if self.instance:
            attributes: dict = self.instance.attributes
            attributes.update(self.validated_data.get("attributes", {}))
            self.validated_data["attributes"] = attributes
        return super().save(**kwargs)

    class Meta:

        model = User
        fields = [
            "pk",
            "username",
            "name",
            "is_active",
            "is_superuser",
            "groups",
            "email",
            "avatar",
            "uid",
            "settings",
        ]
        extra_kwargs = {
            "is_active": {
                "read_only": True
            },
            "name": {
                "allow_blank": True
            },
        }
Ejemplo n.º 4
0
class StatisticsSerializer(serializers.Serializer):
    std_dev = FloatField()
    avg = FloatField()
    cor = DictField(child=FloatField())
Ejemplo n.º 5
0
class LedgerComputePlanSerializer(serializers.Serializer):
    traintuples = ComputePlanTraintupleSerializer(many=True, required=False)
    testtuples = ComputePlanTesttupleSerializer(many=True, required=False)
    composite_traintuples = ComputePlanCompositeTrainTupleSerializer(
        many=True, required=False)
    aggregatetuples = ComputePlanAggregatetupleSerializer(many=True,
                                                          required=False)
    tag = serializers.CharField(min_length=0,
                                max_length=64,
                                allow_blank=True,
                                required=False,
                                allow_null=True)
    metadata = DictField(child=CharField(), required=False, allow_null=True)
    clean_models = serializers.BooleanField(required=False)

    def get_args(self, key, data):
        # convert snake case fields to camel case fields to match chaincode expected inputs
        traintuples = []
        for data_traintuple in data.get('traintuples', []):
            traintuple = {
                'key': uuid.uuid4(),
                'data_manager_key': data_traintuple['data_manager_key'],
                'data_sample_keys': data_traintuple['train_data_sample_keys'],
                'algo_key': data_traintuple['algo_key'],
                'id': data_traintuple['traintuple_id'],
                'metadata': data_traintuple.get('metadata'),
            }
            if 'in_models_ids' in data_traintuple:
                traintuple['in_models_ids'] = data_traintuple['in_models_ids']
            if 'tag' in data_traintuple:
                traintuple['tag'] = data_traintuple['tag']

            traintuples.append(traintuple)

        testtuples = []
        for data_testtuple in data.get('testtuples', []):
            testtuple = {
                'key': uuid.uuid4(),
                'traintuple_id': data_testtuple['traintuple_id'],
                'objective_key': data_testtuple['objective_key'],
                'metadata': data_testtuple.get('metadata'),
            }
            if 'tag' in data_testtuple:
                testtuple['tag'] = data_testtuple['tag']
            if 'data_manager_key' in data_testtuple:
                testtuple['data_manager_key'] = data_testtuple[
                    'data_manager_key']
            if 'test_data_sample_keys' in data_testtuple:
                testtuple['data_sample_keys'] = data_testtuple[
                    'test_data_sample_keys']

            testtuples.append(testtuple)

        composite_traintuples = []
        for data_composite_traintuple in data.get('composite_traintuples', []):
            composite_traintuple = {
                'key':
                uuid.uuid4(),
                'algo_key':
                data_composite_traintuple['algo_key'],
                'data_manager_key':
                data_composite_traintuple['data_manager_key'],
                'data_sample_keys':
                data_composite_traintuple['train_data_sample_keys'],
                'id':
                data_composite_traintuple['composite_traintuple_id'],
                'metadata':
                data_composite_traintuple.get('metadata'),
            }

            if 'tag' in data_composite_traintuple:
                composite_traintuple['tag'] = data_composite_traintuple['tag']
            if 'in_head_model_id' in data_composite_traintuple:
                composite_traintuple[
                    'in_head_model_id'] = data_composite_traintuple[
                        'in_head_model_id']
            if 'in_trunk_model_id' in data_composite_traintuple:
                composite_traintuple[
                    'in_trunk_model_id'] = data_composite_traintuple[
                        'in_trunk_model_id']
            if 'out_trunk_model_permissions' in data_composite_traintuple:
                composite_traintuple['out_trunk_model_permissions'] = {
                    'process': {
                        'authorized_ids':
                        data_composite_traintuple[
                            'out_trunk_model_permissions']['authorized_ids']
                    }
                }

            composite_traintuples.append(composite_traintuple)

        aggregatetuples = []
        for data_aggregatetuple in data.get('aggregatetuples', []):
            aggregatetuple = {
                'key': uuid.uuid4(),
                'algo_key': data_aggregatetuple['algo_key'],
                'worker': data_aggregatetuple['worker'],
                'id': data_aggregatetuple['aggregatetuple_id'],
                'metadata': data_aggregatetuple.get('metadata'),
            }

            if 'in_models_ids' in data_aggregatetuple:
                aggregatetuple['in_models_ids'] = data_aggregatetuple[
                    'in_models_ids']
            if 'tag' in data_aggregatetuple:
                aggregatetuple['tag'] = data_aggregatetuple['tag']

            aggregatetuples.append(aggregatetuple)

        return {
            'key': key,
            'traintuples': traintuples,
            'testtuples': testtuples,
            'composite_traintuples': composite_traintuples,
            'aggregatetuples': aggregatetuples,
            'metadata': data.get('metadata'),
            'tag': data.get('tag'),
            'clean_models': data.get('clean_models', False),
        }

    def create(self, channel_name, key, validated_data):
        args = self.get_args(key, validated_data)
        return ledger.assets.create_computeplan(channel_name, args)

    def update(self, channel_name, key, validated_data):
        args = self.get_args(key, validated_data)
        del args['tag']
        return ledger.assets.update_computeplan(channel_name, args)
Ejemplo n.º 6
0
class AutosubmitChallenge(Challenge):
    """Autosubmit challenge used to send and navigate a POST request"""

    url = CharField()
    attrs = DictField(child=CharField())
Ejemplo n.º 7
0
class AutosubmitChallenge(Challenge):
    """Autosubmit challenge used to send and navigate a POST request"""

    url = CharField()
    attrs = DictField(child=CharField())
    component = CharField(default="ak-stage-autosubmit")
Ejemplo n.º 8
0
class ProjectSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    version = serializers.IntegerField(read_only=True)
    name = serializers.CharField()
    properties = DictField(child=ExtensiblePropertySerializer(read_only=True))
    type_full_name = serializers.CharField()
Ejemplo n.º 9
0
class WorkBatchDetailsSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(read_only=True)
    properties = DictField(child=ExtensiblePropertySerializer(),
                           allow_null=True)
    created_at = serializers.DateTimeField(read_only=True)
    updated_at = serializers.DateTimeField(read_only=True)
    cls_full_name = serializers.CharField(read_only=True)

    # These are still mocked
    transitions = serializers.SerializerMethodField(read_only=True)
    substances = serializers.SerializerMethodField(read_only=True)
    containers = serializers.SerializerMethodField(read_only=True)
    tabs = serializers.SerializerMethodField(read_only=True)

    def update(self, instance, validated_data):
        if validated_data['properties'] is None:
            return instance
        for p in validated_data['properties']:
            setattr(instance, p, validated_data['properties'][p]['value'])
        instance.save()
        return instance

    # TODO: These are mocked for now
    def get_transitions(self, obj):
        return [{
            'source': 1,
            'target': 3,
            'type': 'spawn'
        }  # Substance 1 transitions to substance 3
                ]

    def get_containers(self, obj):
        return {'source': [9], 'target': [10]}

    def get_substances(self, obj):
        return [1, 3]

    def get_tabs(self, obj):
        return [
            {
                'title': 'Move samples',
                'active': True,
                'id': 1,
                'key': 'transition'
            },
            {
                'title': 'Files',
                'active': False,
                'id': 2,
                'key': 'files'
            },
            {
                'title': 'Details',
                'active': False,
                'id': 3,
                'key': 'details'
            },
            {
                'title': 'Comments',
                'active': False,
                'id': 4,
                'key': 'comments'
            },
        ]
Ejemplo n.º 10
0
class EventTopPerUserSerializer(PassiveSerializer):
    """Response object of Event's top_per_user"""

    application = DictField()
    counted_events = IntegerField()
    unique_users = IntegerField()
Ejemplo n.º 11
0
class UILoginButtonSerializer(PassiveSerializer):
    """Serializer for Login buttons of sources"""

    name = CharField()
    challenge = DictField()
    icon_url = CharField(required=False, allow_null=True)