Beispiel #1
0
class ConfigurationSerializer(serializers.Serializer):
    priority = fields.ChoiceField(PRIORITY)
    scheduler = fields.ChoiceField(SCHEDULER_TYPE)
    max_tasks = fields.IntegerField(min_value=1)
    weight = fields.ChoiceField(DECISION_WEIGHT)

    parallelism = fields.ListField(child=fields.RegexField(r'^\d+(\.\d+)?$'),
                                   min_length=4,
                                   max_length=4)

    memory = fields.FloatField()
    cpu_num = fields.IntegerField(allow_null=True, min_value=1)
    disk_size = fields.FloatField()
    cpu_model = fields.CharField(default='', allow_null=True, allow_blank=True)
    cpu_time_exec_cmds = fields.FloatField()
    memory_exec_cmds = fields.FloatField()

    console_level = fields.ChoiceField(LOGGING_LEVELS)
    file_level = fields.ChoiceField(LOGGING_LEVELS)
    console_formatter = fields.CharField()
    file_formatter = fields.CharField()

    keep_intermediate_files = fields.BooleanField()
    upload_verifier_files = fields.BooleanField()
    upload_other_files = fields.BooleanField()
    ignore_subjobs = fields.BooleanField()
    total_coverage = fields.BooleanField()
    coverage_details = fields.ChoiceField(COVERAGE_DETAILS)

    def create(self, validated_data):
        raise NotImplementedError

    def update(self, instance, validated_data):
        raise NotImplementedError
Beispiel #2
0
class HistorySerializerMixIn(Serializer):
    history_id = fields.IntegerField()
    history_date = fields.DateTimeField()
    history_change_reason = fields.CharField()
    history_type = fields.CharField()
    history_user_id = fields.IntegerField()
    history_user = UserSerializer()

    class Meta:
        fields = ('history_id', 'history_date', 'history_change_reason',
                  'history_type', 'history_type', 'history_user_id',
                  'history_user')

    def to_representation(self, instance):
        ret = OrderedDict()
        fields = self._readable_fields  # noqa

        for field in fields:
            simplify_nested_serializer(field)
            try:
                attribute = field.get_attribute(instance)
                if attribute is not None:
                    ret[field.field_name] = field.to_representation(attribute)
                else:
                    ret[field.field_name] = None
            except AttributeError:
                ret[field.field_name] = None

        return ret
Beispiel #3
0
class BadgeSerializer(serializers.ModelSerializer):
    """The badge serializer
    """
    badge_type = fields.SerializerMethodField()
    award_count = fields.IntegerField(source='users__count')
    rank = fields.SerializerMethodField()
    badge_id = fields.IntegerField(source='pk')

    class Meta:
        model = models.Badge
        fields = ('badge_type', 'award_count', 'rank', 'badge_id', 'name')

    @staticmethod
    def get_badge_type(badge: models.Badge) -> str:
        """Get the badge type.

        :param badge: The badges.
        :return: The badge type.
        """
        return "tag_based" if badge.tag_based else "named"

    @staticmethod
    def get_rank(badge: models.Badge) -> str:
        """Get the badge rank.

        :param badge: The badges.
        :return: The badge type.
        """
        for class_id, class_description in models.Badge.CLASS_CHOICES:
            if badge.badge_class == class_id:
                return class_description
Beispiel #4
0
class CreateSightingSerializer(serializers.ModelSerializer):

    id = fields.IntegerField(read_only=True)
    pk = fields.IntegerField(read_only=True)
    photo_url = JsonBase64ImageFileField(required=False, max_length=512)

    class Meta:
        model = Sighting
        fields = (
            'pk',
            'id',
            'accuracy',
            'activity',
            'count',
            'depth',
            'habitat',
            'latitude',
            'longitude',
            'notes',
            'other_species',
            'photo_caption',
            'photo_url',
            'sex',
            'sighting_date',
            'size',
            'size_method',
            'species',
            'time',
            'water_temperature',
            'weight',
            'weight_method',
        )
Beispiel #5
0
class StockTransferOutSerializer(ModelSerializer):
    id = fields.CharField(required=False)
    detail = StockTransferOutDetailSerializer(source='list_detail', many=True, read_only=True)
    created_at = fields.DateTimeField(read_only=True)
    created_by_detail = UserSerializer(read_only=True, source='created_by')
    created_by__id = fields.CharField(read_only=True)
    total = fields.IntegerField(read_only=True)
    promotion__id = fields.IntegerField(required=False, read_only=True)
    promotion_detail = PromotionSerializer(read_only=True, source='promotion')
    customer_detail = CustomerSerializer(read_only=True, source='customer')
    customer__id = fields.CharField(read_only=True)

    def validate_promotion_code(self, promotion_code):
        if promotion_code is None or promotion_code == "":
            return None
        promotions = Promotion.objects.filter(code=promotion_code)
        if promotions.count() == 0:
            raise ValidationError('promotion does not exist')
        if promotions[0].is_used:
            raise ValidationError('promotion is used')
        return promotion_code

    class Meta:
        model = StockTransferOut
        fields = '__all__'
Beispiel #6
0
class NoticeFilterSerializer(serializers.Serializer):
    offset = fields.IntegerField(required=False, default=0, min_value=0)
    limit = fields.IntegerField(required=False,
                                default=3,
                                min_value=0,
                                max_value=10)
    date_after = fields.IntegerField(required=False, default=0, min_value=0)
Beispiel #7
0
    def test_options_mapping(self, assert_dict_equals):
        """
        Confirm that new serializers will catch and correctly manage
        field options for its specified model, for non-embedded models
        """
        class TestSerializer(DjongoModelSerializer):
            class Meta:
                model = OptionsModel
                fields = '__all__'

        expected_dict = {
            # Primary keys should be made read-only, with the db column being
            # ignored entirely
            "db_column_id":
            rmd_fields.ObjectIdField(read_only=True),
            # Nullable and blank values should have required=False appended.
            # The prior requires a unique validator as well, the text requires
            # templates
            "null_char":
            ("CharField(allow_null=True, "
             "required=False, "
             "validators=[<django.core.validators.MaxLengthValidator object>])"
             ),
            "blank_char":
            drf_fields.CharField(allow_blank=True,
                                 required=False,
                                 style={'base_template': 'textarea.html'}),
            # Fields with choices should be coerced into that form of field
            "choice_char":
            "ChoiceField(choices=['Foo', 'Bar', 'Baz'], "
            "validators=[<django.core.validators.MaxLengthValidator object>])",
            # Defaults are handled by Django, not DRF, so the argument should
            # be stripped implicitly (though it still is in use during save!)
            # This will set required=False, however
            "default_email":
            drf_fields.EmailField(max_length=254, required=False),
            # Read only fields should be marked as such
            "read_only_int":
            drf_fields.IntegerField(read_only=True),
            # Errors, by default, should be distinct between DRF and Djongo;
            # Therefore, it should be stripped unless explicitly set in the
            # serializer by the user
            "custom_error":
            drf_fields.IntegerField(max_value=2147483647,
                                    min_value=-2147483648),
            # Help text should be conserved
            "help_char":
            ("CharField(help_text='Super helpful text', "
             "validators=[<django.core.validators.MaxLengthValidator object>])"
             ),
            # Fields designated as unique should have a validator stating
            # such added
            "unique_int":
            ("IntegerField(max_value=2147483647, "
             "min_value=-2147483648, "
             "validators=[<UniqueValidator(queryset=OptionsModel.objects.all())>])"
             ),
        }

        assert_dict_equals(TestSerializer().get_fields(), expected_dict)
Beispiel #8
0
class VodRequestSerializer(serializers.Serializer):
    deck_id = fields.CharField(required=False)
    user_id = fields.IntegerField(required=False)
    archetype_id = fields.IntegerField(required=False)

    def validate_deck_id(self, value):
        if not value:
            return None

        try:
            if value.isdigit():
                deck = Deck.objects.get(id=value)
            else:
                deck = Deck.objects.get_by_shortid(value)
        except Deck.DoesNotExist:
            raise serializers.ValidationError("Invalid deck ID")

        if not deck.is_full_deck:
            raise serializers.ValidationError("Invalid deck ID")

        return deck.id

    def validate_user_id(self, value):
        if not value:
            return None

        User = get_user_model()

        try:
            user = User.objects.get(pk=value)
        except User.DoesNotExist:
            raise serializers.ValidationError("Invalid user ID")

        return user.id

    def validate_archetype_id(self, value):
        if not value:
            return None

        try:
            archetype = Archetype.objects.get(id=value)
        except Archetype.DoesNotExist:
            raise serializers.ValidationError("Invalid archetype ID")

        return archetype.id

    def validate(self, data):
        fields = ["user_id", "deck_id", "archetype_id"]
        field_data = [data.get(field, None) for field in fields]
        valid_fields = sum(1 for field in field_data if field)

        if valid_fields < 1:
            raise serializers.ValidationError("%s must be specified." %
                                              " or ".join(fields))

        if valid_fields > 1:
            raise serializers.ValidationError(
                "Too many identifiers. Only %s must be specified." %
                " or ".join(fields))
        return data
Beispiel #9
0
class NetworkCreateSerializer(NetworkSerializer):
    """Used for POST on Networks."""
    cidr = fields.CharField(
        write_only=True, required=False, label='CIDR',
        help_text=(
            'IPv4/IPv6 CIDR address. If provided, this overrides the value of '
            'network_address & prefix_length. If not provided, '
            'network_address & prefix_length are required.'
        )
    )
    network_address = fields.ModelField(
        model_field=models.Network._meta.get_field('network_address'),
        required=False,
        label=get_field_attr(
            models.Network, 'network_address', 'verbose_name'
        ),
        help_text=get_field_attr(
            models.Network, 'network_address', 'help_text'
        ),
    )
    prefix_length = fields.IntegerField(
        required=False,
        label=get_field_attr(models.Network, 'prefix_length', 'verbose_name'),
        help_text=get_field_attr(models.Network, 'prefix_length', 'help_text'),
    )
    site_id = fields.IntegerField(
        label=get_field_attr(models.Network, 'site', 'verbose_name'),
        help_text=get_field_attr(models.Network, 'site', 'help_text')
    )

    class Meta:
        model = models.Network
        fields = ('cidr', 'network_address', 'prefix_length', 'attributes',
                  'state', 'site_id')
Beispiel #10
0
class MerchandiseSerializer(ModelSerializer):
    id = fields.CharField(required=False)
    type_detail = MerchandiseTypeSerializer(source='type', read_only=True)
    merchandise_type = fields.IntegerField(read_only=True)
    available_count = fields.IntegerField(read_only=True)
    type__id = fields.CharField(read_only=True)

    class Meta:
        model = Merchandise
        fields = '__all__'
Beispiel #11
0
class CustomerTypeSerializer(ModelSerializer):
    id = fields.CharField(required=False)
    min = fields.IntegerField(default=0)
    max = fields.IntegerField(default=0)
    type = fields.CharField(max_length=64)
    descriptions = fields.CharField(max_length=256)

    class Meta:
        model = CustomerType
        fields = '__all__'
class PollResponseSerializer(serializers.MongoEngineModelSerializer):
    phone = fields.CharField(source='phone_no')
    time = fields.DateTimeField(source='received_at')
    relayer = fields.IntegerField(source='relayer_id')
    run = fields.IntegerField(source='run_id')
    source = serialiserzz.Field(source='source')
    location = serialiserzz.Field(source='location_str')

    class Meta:
        model = PollResponse
        fields = ('id', 'phone', 'time', 'relayer', 'run', 'text', 'source', 'location', 'poll')
Beispiel #13
0
class RapidProMessageSerializer(serializers.MongoEngineModelSerializer):
    phone = fields.CharField(source='phone_no')
    time = RapidProDateTimeField(source='received_at')
    relayer = fields.IntegerField(source='relayer_id')
    run = fields.IntegerField(source='run_id')
    source = serialiserzz.Field(source='source')
    profile_id = serialiserzz.Field(source='profile_id')
    location = serialiserzz.Field(source='location_str')

    class Meta:
        model = RapidProMessage
        fields = ('id', 'phone', 'time', 'relayer', 'run', 'text', 'source',
                  'location', 'disaster', 'profile_id', 'auto_associated')
Beispiel #14
0
class VodSerializer(serializers.Serializer):
    """A serializer to extract from a TwitchVod model instance"""
    channel_name = fields.CharField(source="twitch_channel_name")
    url = fields.URLField()
    game_date = TimestampField(precision=1)
    game_type = fields.CharField()
    rank = fields.IntegerField()
    legend_rank = fields.IntegerField(allow_null=True)
    friendly_player_archetype_id = fields.IntegerField(allow_null=True)
    opposing_player_class = fields.CharField()
    opposing_player_archetype_id = fields.IntegerField(allow_null=True)
    won = fields.BooleanField()
    went_first = fields.BooleanField()
    game_length_seconds = fields.IntegerField()
    replay_shortid = fields.CharField()
Beispiel #15
0
class CardboardWishSerializer(serializers.ModelSerializer):
    created_at = serializers.DateTimeField(read_only=True,
                                           format=JAVASCRIPT_DATETIME_FORMAT)
    updated_at = serializers.DateTimeField(read_only=True,
                                           format=JAVASCRIPT_DATETIME_FORMAT)
    requirements = RequirementSerializer(many=True, read_only=True)
    wish_id = fields.IntegerField(write_only=True)
    cardboard = CardboardNameSerializer(validators=[_validate_cardboard_name],
                                        source='cardboard_name')
    minimum_amount = fields.IntegerField(required=False)

    class Meta:
        model = models.CardboardWish
        fields = ('id', 'cardboard', 'minimum_amount', 'requirements',
                  'created_at', 'updated_at', 'wish_id')
Beispiel #16
0
class ProfileSerializer(serializers.DocumentSerializer):
    name = fields.CharField(required=False)
    age = fields.IntegerField(required=False)

    class Meta:
        model = models.Profile
        fields = ['id', 'name', 'age']
Beispiel #17
0
    def test_inherited_field_nullable(self, assert_dict_equals):
        """
        Confirm the fields declared in a serializer that another
        serializer inherits from can still be ignored by setting them to
        `None` in the child serializer
        """
        class TestSerializer(DjongoModelSerializer):
            missing = ReadOnlyField()

            class Meta:
                model = ObjIDModel
                fields = '__all__'

        class ChildSerializer(TestSerializer):
            missing = None

            class Meta(TestSerializer.Meta):
                pass

        expected_dict = {
            '_id':
            rmd_fields.ObjectIdField(read_only=True),
            'int_field':
            drf_fields.IntegerField(max_value=2147483647,
                                    min_value=-2147483648),
            'char_field':
            drf_fields.CharField(max_length=5),
        }

        assert_dict_equals(ChildSerializer().get_fields(), expected_dict)
Beispiel #18
0
class LotesSerializer(serializers.EmbeddedDocumentSerializer):
    existencia = fields.IntegerField(required=True)
    fecha_vencimiento = fields.DateField(required=False)

    class Meta:
        model = Lote
        fields = "__all__"
Beispiel #19
0
class CopyPageAPIActionSerializer(Serializer):
    # Note: CopyPageAction will validate the destination page
    destination_page_id = fields.IntegerField(required=False)
    recursive = fields.BooleanField(default=False, required=False)
    keep_live = fields.BooleanField(default=True, required=False)
    slug = fields.CharField(required=False)
    title = fields.CharField(required=False)
Beispiel #20
0
class OccurrenceSerializer(serializers.HyperlinkedModelSerializer):
    id = fields.IntegerField(read_only=True)
    url = fields.SerializerMethodField()
    methods = fields.SerializerMethodField()
    _methods_cache = None  # class attribute that caches methdos for the OccurrenceViewSet

    class Meta:
        model = Occurrence

    def get_methods(self, occ):
        from views import OccurrenceViewSet  # @NoMove
        methods = OccurrenceSerializer._methods_cache or get_detail_routes(
            OccurrenceViewSet)
        OccurrenceSerializer._methods_cache = methods
        method_dict = {}
        lookups = occ.get_lookups()
        for method in methods:
            url_name = "occurrence-{0}".format(method)
            try:
                url = reverse(url_name,
                              args=lookups.values(),
                              request=self._context['request'])
            except NoReverseMatch:
                pass
            else:
                method_dict[method] = url
        return method_dict

    def get_url(self, occ):
        lookups = occ.get_lookups()
        return reverse('occurrence-detail',
                       args=lookups.values(),
                       request=self._context['request'])
Beispiel #21
0
class NetworkCreateSerializer(NetworkSerializer):
    """Used for POST on Networks."""
    cidr = fields.CharField(write_only=True)
    site_id = fields.IntegerField()

    class Meta:
        model = models.Network
        fields = ('cidr', 'attributes', 'site_id')

    def create(self, validated_data):

        # Remove the related fields before we write the object
        attributes = validated_data.pop('attributes', {})

        obj = super(NetworkCreateSerializer, self).create(validated_data)

        # Try to populate the related fields and if there are any validation
        # problems, delete the object and re-raise the error. If not, save the
        # changes.
        try:
            obj.set_attributes(attributes)
        except exc.ValidationError:
            obj.delete()
            raise
        else:
            obj.save()

        return obj
Beispiel #22
0
class UserBadgeSerializer(serializers.ModelSerializer):
    """The user badge serializer
    """
    user = BaseUserSerializer()
    name = fields.CharField(source='badge.name')
    badge_type = fields.SerializerMethodField(source='badge.badge_type')
    rank = fields.SerializerMethodField(source='badge.rank')
    badge_id = fields.IntegerField(source='pk')

    class Meta:
        model = models.UserBadge
        fields = ('user', 'badge_type', 'rank', 'badge_id', 'name')

    @staticmethod
    def get_badge_type(user_badge: models.UserBadge) -> str:
        """Get the user badge type.

        :param user_badge: The badges.
        :return: The badge type.
        """
        return "tag_based" if user_badge.badge.tag_based else "named"

    @staticmethod
    def get_rank(user_badge: models.UserBadge) -> str:
        """Get the user badge rank.

        :param user_badge: The badges.
        :return: The badge type.
        """
        for class_id, class_description in models.Badge.CLASS_CHOICES:
            if user_badge.badge.badge_class == class_id:
                return class_description
Beispiel #23
0
class FacebookSerializer(serializers.Serializer):
    id = fields.IntegerField(read_only=True)
    access_token = fields.CharField(max_length=255)
    auth_token = fields.CharField(max_length=255, read_only=True)

    def save(self, **kwargs):
        pass
Beispiel #24
0
 def get_extend_param_fields(cls):
     assert 0 < cls.DEFAULT_PAGE_SIZE <= cls.PAGE_SIZE_MAX, (
         "DEFAULT_PAGE_SIZE mast between 0 and PAGE_SIZE_MAX in class %s" %
         cls.__name__)
     return super().get_extend_param_fields() + (
         ('page',
          fields.IntegerField(label=gettext_lazy('Page number'),
                              default=1,
                              help_text=gettext_lazy('Start with %(start)s')
                              % {'start': 1})),
         ('page_size',
          fields.IntegerField(label=gettext_lazy('Page size'),
                              default=cls.DEFAULT_PAGE_SIZE,
                              min_value=1,
                              max_value=cls.PAGE_SIZE_MAX)),
     )
Beispiel #25
0
class CarSerializer(serializers.ModelSerializer):
    id = fields.IntegerField(required=True)
    plates = fields.CharField(read_only=True)

    class Meta:
        model = Car
        fields = ("id", "plates", "fuel_consumption", "description")
Beispiel #26
0
class CounterItemSerializer(ModelSerializer):

    count = fields.IntegerField(required=True)

    class Meta:
        model = CounterItem
        fields = ['id', 'count']
Beispiel #27
0
    def get_fields(self):
        flds = {f : fields.IntegerField() for f in ["articles", "done","error"]}
        flds["plugin_id"] = relations.PrimaryKeyRelatedField(queryset=Plugin.objects.all())
        flds[ "article__articlesets_set"] = relations.PrimaryKeyRelatedField(queryset=ArticleSet.objects.all())
        flds["article__articlesets_set__project"] = relations.PrimaryKeyRelatedField(queryset=Project.objects.all())

        return flds
Beispiel #28
0
class StockTransferInSerializer(ModelSerializer):
    id = fields.CharField(required=False)
    detail = StockTransferInDetailSerializer(source='list_detail',
                                             many=True,
                                             read_only=True)
    created_at = fields.DateTimeField(read_only=True)
    total = fields.IntegerField(read_only=True)
    dept = fields.IntegerField(read_only=True)
    supplier_detail = SupplierSerializer(read_only=True, source='supplier')
    created_by_detail = UserSerializer(read_only=True, source='created_by')
    created_by__id = fields.CharField(read_only=True)
    supplier__id = fields.CharField(read_only=True)

    class Meta:
        model = StockTransferIn
        fields = '__all__'
class QuoteSerializer(serializers.Serializer):
    id = fields.IntegerField(read_only=True)
    text = fields.CharField()
    author = fields.CharField(max_length=300)

    def create(self, validated_data):
        return Quote.objects.create(**validated_data)
Beispiel #30
0
class DeviceCreateSerializer(DeviceSerializer):
    """Used for POST on Devices."""
    site_id = fields.IntegerField()

    class Meta:
        model = models.Device
        fields = ('hostname', 'attributes', 'site_id')

    def create(self, validated_data):

        # Remove the related fields before we write the object
        attributes = validated_data.pop('attributes', {})

        # Save the base object to the database.
        obj = super(DeviceCreateSerializer, self).create(validated_data)

        # Try to populate the related fields and if there are any validation
        # problems, delete the object and re-raise the error. If not, save the
        # changes.
        try:
            obj.set_attributes(attributes)
        except exc.ValidationError:
            obj.delete()
            raise
        else:
            obj.save()

        return obj