Ejemplo n.º 1
0
class RepositoryVersionSerializer(ModelSerializer,
                                  NestedHyperlinkedModelSerializer):
    pulp_href = NestedIdentityField(
        view_name='versions-detail',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )
    number = serializers.IntegerField(read_only=True)
    base_version = NestedRelatedField(
        required=False,
        help_text=_(
            'A repository version whose content was used as the initial set of content '
            'for this repository version'),
        queryset=models.RepositoryVersion.objects.all(),
        view_name='versions-detail',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )
    content_summary = ContentSummarySerializer(
        help_text=_(
            'Various count summaries of the content in the version and the HREF to view '
            'them.'),
        source="*",
        read_only=True,
    )

    class Meta:
        model = models.RepositoryVersion
        fields = ModelSerializer.Meta.fields + (
            'pulp_href',
            'number',
            'base_version',
            'content_summary',
        )
Ejemplo n.º 2
0
class RepositoryVersionSerializer(ModelSerializer,
                                  NestedHyperlinkedModelSerializer):
    _href = NestedIdentityField(
        view_name='versions-detail',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )
    number = serializers.IntegerField(read_only=True)
    base_version = NestedRelatedField(
        required=False,
        help_text=_(
            'A repository version whose content was used as the initial set of content '
            'for this repository version'),
        queryset=models.RepositoryVersion.objects.all(),
        view_name='versions-detail',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )
    content_summary = serializers.SerializerMethodField(
        help_text=_(
            'Various count summaries of the content in the version and the HREF to view '
            'them.'),
        read_only=True,
    )

    def get_content_summary(self, obj):
        """
        The summary of contained content.

        Returns:
            dict: The dictionary has the following format.::

                {
                    'added': {<_type>: {'count': <count>, 'href': <href>},
                    'removed': {<_type>: {'count': <count>, 'href': <href>},
                    'present': {<_type>: {'count': <count>, 'href': <href>},
                }

        """
        to_return = {'added': {}, 'removed': {}, 'present': {}}
        for count_detail in obj.counts.all():
            count_type = count_detail.get_count_type_display()
            item_dict = {
                'count': count_detail.count,
                'href': count_detail.content_href
            }
            to_return[count_type][count_detail.content_type] = item_dict
        return to_return

    class Meta:
        model = models.RepositoryVersion
        fields = ModelSerializer.Meta.fields + (
            '_href',
            'number',
            'base_version',
            'content_summary',
        )
Ejemplo n.º 3
0
class RepositoryVersionSerializer(ModelSerializer,
                                  NestedHyperlinkedModelSerializer):
    _href = NestedIdentityField(
        view_name='versions-detail',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )
    _content_href = NestedIdentityField(
        view_name='versions-content',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )
    _added_href = NestedIdentityField(
        view_name='versions-added-content',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )
    _removed_href = NestedIdentityField(
        view_name='versions-removed-content',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )
    number = serializers.IntegerField(read_only=True)
    content_summary = serializers.DictField(help_text=_(
        'A list of counts of each type of content in this version.'),
                                            read_only=True)
    base_version = NestedRelatedField(
        required=False,
        help_text=_(
            'A repository version whose content was used as the initial set of content '
            'for this repository version'),
        queryset=models.RepositoryVersion.objects.all(),
        view_name='versions-detail',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )

    class Meta:
        model = models.RepositoryVersion
        fields = ModelSerializer.Meta.fields + (
            '_href', '_content_href', '_added_href', '_removed_href', 'number',
            'content_summary', 'base_version')
Ejemplo n.º 4
0
class GroupRoleSerializer(ModelSerializer, NestedHyperlinkedModelSerializer):
    """Serializer for GroupRole."""

    pulp_href = NestedIdentityField(
        view_name="roles-detail", parent_lookup_kwargs={"group_pk": "group__pk"}
    )

    role = serializers.SlugRelatedField(
        slug_field="name",
        queryset=Role.objects.all(),
    )

    content_object = ContentObjectField(
        help_text=_("Optional pulp_href of the object the permissions are to be asserted on."),
        source="*",
        allow_null=True,
    )

    def validate(self, data):
        data = super().validate(data)
        data["group"] = Group.objects.get(
            pk=self.context["request"].resolver_match.kwargs["group_pk"]
        )

        natural_key_args = {
            "group_id": data["group"].pk,
            "role_id": data["role"].pk,
            "object_id": None,
            "content_type": None,
        }
        content_object = data["content_object"]
        if content_object:
            content_type = ContentType.objects.get_for_model(
                content_object, for_concrete_model=False
            )
            if not data["role"].permissions.filter(content_type__pk=content_type.id).exists():
                raise serializers.ValidationError(
                    _("The role '{}' does not carry any permission for that object.").format(
                        data["role"].name
                    )
                )
            natural_key_args["object_id"] = content_object.pk
            natural_key_args["content_type"] = content_type
        if self.Meta.model.objects.filter(**natural_key_args).exists():
            raise serializers.ValidationError(_("The role is already assigned to this group."))
        return data

    class Meta:
        model = GroupRole
        fields = ModelSerializer.Meta.fields + ("role", "content_object")
Ejemplo n.º 5
0
class RepositoryVersionSerializer(ModelSerializer,
                                  NestedHyperlinkedModelSerializer):
    _href = NestedIdentityField(
        view_name='versions-detail',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )
    number = serializers.IntegerField(read_only=True)
    base_version = NestedRelatedField(
        required=False,
        help_text=_(
            'A repository version whose content was used as the initial set of content '
            'for this repository version'),
        queryset=models.RepositoryVersion.objects.all(),
        view_name='versions-detail',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
    )
    content_hrefs = serializers.SerializerMethodField(
        help_text=_(
            'A mapping of the types of content in this version, and the HREF to view '
            'them.'),
        read_only=True,
    )
    content_added_hrefs = serializers.SerializerMethodField(
        help_text=_(
            'A mapping of the types of content added in this version, and the HREF to '
            'view them.'),
        read_only=True,
    )
    content_removed_hrefs = serializers.SerializerMethodField(
        help_text=_(
            'A mapping of the types of content removed from this version, and the HREF '
            'to view them.'),
        read_only=True,
    )
    content_summary = serializers.SerializerMethodField(
        help_text=_(
            'A list of counts of each type of content in this version.'),
        read_only=True,
    )
    content_added_summary = serializers.SerializerMethodField(
        help_text=_(
            'A list of counts of each type of content added in this version.'),
        read_only=True,
    )
    content_removed_summary = serializers.SerializerMethodField(
        help_text=_(
            'A list of counts of each type of content removed in this version.'
        ),
        read_only=True,
    )

    def get_content_summary(self, obj):
        """
        The summary of contained content.

        Returns:
            dict: of {<_type>: <count>}
        """
        annotated = obj.content.values('_type').annotate(count=Count('_type'))
        return {c['_type']: c['count'] for c in annotated}

    def get_content_added_summary(self, obj):
        """
        The summary of added content.

        Returns:
            dict: of {<_type>: <count>}
        """
        annotated = obj.added().values('_type').annotate(count=Count('_type'))
        return {c['_type']: c['count'] for c in annotated}

    def get_content_removed_summary(self, obj):
        """
        The summary of removed content.

        Returns:
            dict: of {<_type>: <count>}
        """
        annotated = obj.removed().values('_type').annotate(
            count=Count('_type'))
        return {c['_type']: c['count'] for c in annotated}

    def get_content_hrefs(self, obj):
        """
        Generate URLs for the content types present in the RepositoryVersion.

        For each content type present in the RepositoryVersion, create the URL of the viewset of
        that variety of content along with a query parameter which filters it by presence in this
        RepositoryVersion.

        Args:
            obj (pulpcore.app.models.RepositoryVersion): The RepositoryVersion being serialized.

        Returns:
            dict: {<_type>: <url>}
        """
        content_urls = {}

        for ctype in obj.content.values_list('_type', flat=True).distinct():
            ctype_model = obj.content.filter(
                _type=ctype).first().cast().__class__
            ctype_view = get_view_name_for_model(ctype_model, 'list')
            try:
                ctype_url = reverse(ctype_view)
            except django.urls.exceptions.NoReverseMatch:
                # We've hit a content type for which there is no viewset.
                # There's nothing we can do here, except to skip it.
                continue
            rv_href = "/pulp/api/v3/repositories/{repo}/versions/{version}/".format(
                repo=obj.repository.pk, version=obj.number)
            full_url = "{base}?repository_version={rv_href}".format(
                base=ctype_url, rv_href=rv_href)
            content_urls[ctype] = full_url

        return content_urls

    def get_content_added_hrefs(self, obj):
        """
        Generate URLs for the content types added in the RepositoryVersion.

        For each content type added in the RepositoryVersion, create the URL of the viewset of
        that variety of content along with a query parameter which filters it by addition in this
        RepositoryVersion.

        Args:
            obj (pulpcore.app.models.RepositoryVersion): The RepositoryVersion being serialized.

        Returns:
            dict: {<_type>: <url>}
        """
        content_urls = {}

        for ctype in obj.added().values_list('_type', flat=True).distinct():
            ctype_model = obj.content.filter(
                _type=ctype).first().cast().__class__
            ctype_view = get_view_name_for_model(ctype_model, 'list')
            try:
                ctype_url = reverse(ctype_view)
            except django.urls.exceptions.NoReverseMatch:
                # We've hit a content type for which there is no viewset.
                # There's nothing we can do here, except to skip it.
                continue
            rv_href = "/pulp/api/v3/repositories/{repo}/versions/{version}/".format(
                repo=obj.repository.pk, version=obj.number)
            full_url = "{base}?repository_version_added={rv_href}".format(
                base=ctype_url, rv_href=rv_href)
            content_urls[ctype] = full_url

        return content_urls

    def get_content_removed_hrefs(self, obj):
        """
        Generate URLs for the content types removed in the RepositoryVersion.

        For each content type removed in the RepositoryVersion, create the URL of the viewset of
        that variety of content along with a query parameter which filters it by removal in this
        RepositoryVersion.

        Args:
            obj (pulpcore.app.models.RepositoryVersion): The RepositoryVersion being serialized.

        Returns:
            dict: {<_type>: <url>}
        """
        content_urls = {}

        for ctype in obj.removed().values_list('_type', flat=True).distinct():
            ctype_model = obj.content.filter(
                _type=ctype).first().cast().__class__
            ctype_view = get_view_name_for_model(ctype_model, 'list')
            try:
                ctype_url = reverse(ctype_view)
            except django.urls.exceptions.NoReverseMatch:
                # We've hit a content type for which there is no viewset.
                # There's nothing we can do here, except to skip it.
                continue
            rv_href = "/pulp/api/v3/repositories/{repo}/versions/{version}/".format(
                repo=obj.repository.pk, version=obj.number)
            full_url = "{base}?repository_version_removed={rv_href}".format(
                base=ctype_url, rv_href=rv_href)
            content_urls[ctype] = full_url

        return content_urls

    class Meta:
        model = models.RepositoryVersion
        fields = ModelSerializer.Meta.fields + (
            '_href',
            'number',
            'base_version',
            'content_hrefs',
            'content_added_hrefs',
            'content_removed_hrefs',
            'content_summary',
            'content_added_summary',
            'content_removed_summary',
        )