Exemple #1
0
def validate(attrs, **context):
    if type(attrs) is not dict:
        raise ValidationError('Object must be of type dict')
    if not attrs:
        return
    if is_composite(attrs):
        from avocado.models import DataContext
        try:
            if 'user' in context:
                cxt = DataContext.objects.get(id=attrs['id'], user=context['user'])
            else:
                cxt = DataContext.objects.get(id=attrs['id'])
        except DataContext.DoesNotExist:
            raise ValidationError(u'DataContext "{0}" does not exist.'.format(attrs['id']))
        validate(cxt.json, **context)
    elif is_condition(attrs):
        from avocado.models import DataField, DataConcept

        field_key = attrs.get('field', attrs.get('id'))
        # Parse to get into a consistent format
        field_key = utils.parse_field_key(field_key)

        try:
            if 'concept' in attrs:
                concept = DataConcept.objects.get(id=attrs['concept'])
                field = concept.fields.get(**field_key)
            else:
                field = DataField.objects.get(**field_key)
        except ObjectDoesNotExist, e:
            raise ValidationError(e.message)
        field.validate(operator=attrs['operator'], value=attrs['value'])
Exemple #2
0
    def field(self):
        if not hasattr(self, '_field'):
            from avocado.models import DataField
            # Parse to get into a consistent format
            field_key = utils.parse_field_key(self.field_key)

            if self.concept:
                self._field = self.concept.fields.get(**field_key)
            else:
                self._field = DataField.objects.get(**field_key)
        return self._field
Exemple #3
0
    def field(self):
        if not hasattr(self, '_field'):
            from avocado.models import DataField
            # Parse to get into a consistent format
            field_key = utils.parse_field_key(self.field_key)

            if self.concept:
                self._field = self.concept.fields.get(**field_key)
            else:
                self._field = DataField.objects.get(**field_key)
        return self._field
Exemple #4
0
    def validate_field(self):
        """
        Validate and clean the field.

        If a concept is also available, it will accessible via `self.concept`.
        """
        field = self.data.get('field')

        if not field:
            self.error('field_not_defined')

        concept = self.cleaned_data.get('concept')

        # A non-falsy concept is defined, but no cleaned concept is available.
        # The field cannot be validated
        if self.data.get('concept') and not concept:
            return

        kwargs = utils.parse_field_key(field)

        # If the concept is defined, restrict to the concept, otherwise
        # get from the entire set.
        if concept:
            queryset = concept.fields.all()
        elif 'user' in self.context:
            queryset = DataField.objects.published(user=self.context['user'])
        else:
            queryset = DataField.objects.all()

        try:
            return queryset.get(**kwargs)
        except DataField.DoesNotExist:
            if concept:
                self.error('field_does_not_exist_for_concept')
            self.error('field_does_not_exist')
        except DataField.MultipleObjectsReturned:
            if concept:
                self.error('ambiguous_field_for_concept')
            self.error('ambiguous_field')
Exemple #5
0
    def validate_field(self):
        """
        Validate and clean the field.

        If a concept is also available, it will accessible via `self.concept`.
        """
        field = self.data.get('field')

        if not field:
            self.error('field_not_defined')

        concept = self.cleaned_data.get('concept')

        # A non-falsy concept is defined, but no cleaned concept is available.
        # The field cannot be validated
        if self.data.get('concept') and not concept:
            return

        kwargs = utils.parse_field_key(field)

        # If the concept is defined, restrict to the concept, otherwise
        # get from the entire set.
        if concept:
            queryset = concept.fields.all()
        elif 'user' in self.context:
            queryset = DataField.objects.published(user=self.context['user'])
        else:
            queryset = DataField.objects.all()

        try:
            return queryset.get(**kwargs)
        except DataField.DoesNotExist:
            if concept:
                self.error('field_does_not_exist_for_concept')
            self.error('field_does_not_exist')
        except DataField.MultipleObjectsReturned:
            if concept:
                self.error('ambiguous_field_for_concept')
            self.error('ambiguous_field')
Exemple #6
0
def validate(attrs, **context):
    if not attrs:
        return None

    if type(attrs) is not dict:
        raise ValidationError('Object must be of type dict')

    enabled = attrs.pop('enabled', None)

    attrs.pop('errors', None)
    attrs.pop('warnings', None)
    errors = []
    warnings = []

    if is_composite(attrs):
        from avocado.models import DataContext
        try:
            if 'user' in context:
                cxt = DataContext.objects.get(id=attrs['composite'],
                                              user=context['user'])
            else:
                cxt = DataContext.objects.get(id=attrs['composite'])
            validate(cxt.json, **context)
            attrs['language'] = cxt.name
        except DataContext.DoesNotExist:
            enabled = False
            errors.append(u'DataContext "{0}" does not exist.'
                          .format(attrs['id']))

    elif is_condition(attrs):
        from avocado.models import DataField, DataConcept
        field_key = attrs.get('field', attrs.get('id'))
        # Parse to get into a consistent format
        field_key = utils.parse_field_key(field_key)

        try:
            if 'concept' in attrs:
                concept = DataConcept.objects.get(id=attrs['concept'])
                field = concept.fields.get(**field_key)
            else:
                field = DataField.objects.get(**field_key)
            field.validate(operator=attrs['operator'], value=attrs['value'])
            node = parse(attrs, **context)
            attrs['language'] = node.language['language']

            value = node._meta['cleaned_data']['value']
            cleaned = None

            if field.enumerable or field.simple_type == 'key':
                value_labels = field.value_labels()

                if isinstance(value, QuerySet):
                    cleaned = [{
                        'value': val.pk,
                        'label': value_labels[val.pk]
                    } for val in value]
                elif isinstance(value, (list, tuple)):
                    cleaned = []

                    for val in value:
                        if val in value_labels:
                            label = value_labels[val]
                        else:
                            label = smart_unicode(val)

                        cleaned.append({
                            'value': val,
                            'label': label
                        })
                elif isinstance(value, models.Model):
                    # Values represented by django models
                    # have only one particular label.
                    cleaned = {
                        'value': value.pk,
                        'label': value_labels[value.pk]
                    }
                else:
                    # Handle single, non-model values.
                    if value in value_labels:
                        label = value_labels[value]
                    else:
                        label = smart_unicode(value)

                    cleaned = {
                        'value': value,
                        'label': label,
                    }

            if cleaned:
                attrs['cleaned_value'] = cleaned

        except ObjectDoesNotExist:
            enabled = False
            errors.append('Field does not exist')

    elif is_branch(attrs):
        if attrs['type'] not in LOGICAL_OPERATORS:
            enabled = False
        else:
            map(lambda x: validate(x, **context), attrs['children'])
    else:
        enabled = False
        errors.append('Unknown node type')

    # If this condition was originally disabled, ensure that decision is
    # persisted
    if enabled is False:
        attrs['enabled'] = False

    if errors:
        attrs['errors'] = errors
    if warnings:
        attrs['warnings'] = warnings

    return attrs
Exemple #7
0
def validate(attrs, **context):
    if not attrs:
        return None

    if type(attrs) is not dict:
        raise ValidationError('Object must be of type dict')

    enabled = attrs.pop('enabled', None)

    attrs.pop('errors', None)
    attrs.pop('warnings', None)
    errors = []
    warnings = []

    if is_composite(attrs):
        from avocado.models import DataContext
        try:
            if 'user' in context:
                cxt = DataContext.objects.get(id=attrs['composite'],
                                              user=context['user'])
            else:
                cxt = DataContext.objects.get(id=attrs['composite'])
            validate(cxt.json, **context)
            attrs['language'] = cxt.name
        except DataContext.DoesNotExist:
            enabled = False
            errors.append(u'DataContext "{0}" does not exist.'.format(
                attrs['id']))

    elif is_condition(attrs):
        from avocado.models import DataField, DataConcept
        field_key = attrs.get('field', attrs.get('id'))
        # Parse to get into a consistent format
        field_key = utils.parse_field_key(field_key)

        try:
            if 'concept' in attrs:
                concept = DataConcept.objects.get(id=attrs['concept'])
                field = concept.fields.get(**field_key)
            else:
                field = DataField.objects.get(**field_key)
            field.validate(operator=attrs['operator'], value=attrs['value'])
            node = parse(attrs, **context)
            attrs['language'] = node.language['language']

            value = node._meta['cleaned_data']['value']
            cleaned = None

            if field.enumerable or field.simple_type == 'key':
                value_labels = field.value_labels()

                if isinstance(value, QuerySet):
                    cleaned = [{
                        'value': val.pk,
                        'label': value_labels[val.pk]
                    } for val in value]
                elif isinstance(value, (list, tuple)):
                    cleaned = []

                    for val in value:
                        if val in value_labels:
                            label = value_labels[val]
                        else:
                            label = smart_unicode(val)

                        cleaned.append({'value': val, 'label': label})
                elif isinstance(value, models.Model):
                    # Values represented by django models
                    # have only one particular label.
                    cleaned = {
                        'value': value.pk,
                        'label': value_labels[value.pk]
                    }
                else:
                    # Handle single, non-model values.
                    if value in value_labels:
                        label = value_labels[value]
                    else:
                        label = smart_unicode(value)

                    cleaned = {
                        'value': value,
                        'label': label,
                    }

            if cleaned:
                attrs['cleaned_value'] = cleaned

        except ObjectDoesNotExist:
            enabled = False
            errors.append('Field does not exist')

    elif is_branch(attrs):
        if attrs['type'] not in LOGICAL_OPERATORS:
            enabled = False
        else:
            map(lambda x: validate(x, **context), attrs['children'])
    else:
        enabled = False
        errors.append('Unknown node type')

    # If this condition was originally disabled, ensure that decision is
    # persisted
    if enabled is False:
        attrs['enabled'] = False

    if errors:
        attrs['errors'] = errors
    if warnings:
        attrs['warnings'] = warnings

    return attrs
Exemple #8
0
def validate(attrs, **context):
    if not attrs:
        return None

    if type(attrs) is not dict:
        raise ValidationError('Object must be of type dict')

    enabled = attrs.pop('enabled', None)

    attrs.pop('errors', None)
    attrs.pop('warnings', None)
    errors = []
    warnings = []

    if is_composite(attrs):
        from avocado.models import DataContext
        try:
            if 'user' in context:
                cxt = DataContext.objects.get(id=attrs['composite'],
                                              user=context['user'])
            else:
                cxt = DataContext.objects.get(id=attrs['composite'])
            validate(cxt.json, **context)
            attrs['language'] = cxt.name
        except DataContext.DoesNotExist:
            enabled = False
            errors.append(u'DataContext "{0}" does not exist.'.format(
                attrs['id']))

    elif is_condition(attrs):
        from avocado.models import DataField, DataConcept
        field_key = attrs.get('field', attrs.get('id'))
        # Parse to get into a consistent format
        field_key = utils.parse_field_key(field_key)

        try:
            if 'concept' in attrs:
                concept = DataConcept.objects.get(id=attrs['concept'])
                field = concept.fields.get(**field_key)
            else:
                field = DataField.objects.get(**field_key)
            field.validate(operator=attrs['operator'], value=attrs['value'])
            node = parse(attrs, **context)
            attrs['language'] = node.language['language']
        except ObjectDoesNotExist:
            enabled = False
            errors.append('Field does not exist')

    elif is_branch(attrs):
        if attrs['type'] not in LOGICAL_OPERATORS:
            enabled = False
        else:
            map(lambda x: validate(x, **context), attrs['children'])
    else:
        enabled = False

    # If this condition was originally disabled, ensure that decision is
    # persisted
    if enabled is False:
        attrs['enabled'] = False

    if errors:
        attrs['errors'] = errors
    if warnings:
        attrs['warnings'] = warnings

    return attrs
Exemple #9
0
def validate(attrs, **context):
    if not attrs:
        return None

    if type(attrs) is not dict:
        raise ValidationError('Object must be of type dict')

    enabled = attrs.pop('enabled', None)

    attrs.pop('errors', None)
    attrs.pop('warnings', None)
    errors = []
    warnings = []

    if is_composite(attrs):
        from avocado.models import DataContext
        try:
            if 'user' in context:
                cxt = DataContext.objects.get(id=attrs['composite'],
                                              user=context['user'])
            else:
                cxt = DataContext.objects.get(id=attrs['composite'])
            validate(cxt.json, **context)
            attrs['language'] = cxt.name
        except DataContext.DoesNotExist:
            enabled = False
            errors.append(u'DataContext "{0}" does not exist.'
                          .format(attrs['id']))

    elif is_condition(attrs):
        from avocado.models import DataField, DataConcept
        field_key = attrs.get('field', attrs.get('id'))
        # Parse to get into a consistent format
        field_key = utils.parse_field_key(field_key)

        try:
            if 'concept' in attrs:
                concept = DataConcept.objects.get(id=attrs['concept'])
                field = concept.fields.get(**field_key)
            else:
                field = DataField.objects.get(**field_key)
            field.validate(operator=attrs['operator'], value=attrs['value'])
            node = parse(attrs, **context)
            attrs['language'] = node.language['language']
        except ObjectDoesNotExist:
            enabled = False
            errors.append('Field does not exist')

    elif is_branch(attrs):
        if attrs['type'] not in LOGICAL_OPERATORS:
            enabled = False
        else:
            map(lambda x: validate(x, **context), attrs['children'])
    else:
        enabled = False

    # If this condition was originally disabled, ensure that decision is
    # persisted
    if enabled is False:
        attrs['enabled'] = False

    if errors:
        attrs['errors'] = errors
    if warnings:
        attrs['warnings'] = warnings

    return attrs