Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import os
from django.conf import settings
from rest_framework import serializers
from rest_framework.reverse import reverse
from rest_framework_nested.relations import NestedHyperlinkedRelatedField
from pulpcore.app import models
from pulpcore.app.serializers import DetailRelatedField, RelatedField
class ContentRelatedField(DetailRelatedField):
"""
Serializer Field for use when relating to Content Detail Models
"""
queryset = models.Content.objects.all()
class SingleContentArtifactField(RelatedField):
"""
A serializer field for the '_artifacts' ManyToManyField on the Content model (single-artifact).
"""
lookup_field = 'pk'
view_name = 'artifacts-detail'
queryset = models.Artifact.objects.all()
allow_null = True
def get_attribute(self, instance):
"""
Returns the field from the instance that should be serialized using this serializer field.
This serializer looks up the list of artifacts and returns only one, if any exist. If more
artifact=artifact,
content=version,
relative_path=rel_path,
)
with pulp_models.RepositoryVersion.create(repository) as new_version:
new_version.add_content(
pulp_models.Content.objects.filter(pk=version.pk)
)
publication = pulp_models.Publication.objects.create(
repository_version=new_version,
complete=True,
pass_through=True,
)
pulp_models.Distribution.objects.update_or_create(
name='galaxy',
base_path='galaxy',
defaults={'publication': publication},
)
task.imported_version = version
task.save()
Deletes an incomplete Repository Version
This method deletes a RepositoryVersion only if its 'complete' property is False. All
RepositoryContent added in the deleted RepositoryVersion are deleted also. All
RepositoryContent removed in the deleted RepositoryVersion has the version_removed set to
None.
Raise:
pulpcore.exception.ResourceImmutableError: if delete() is called on a complete
RepositoryVersion
"""
if self._model.complete:
raise ResourceImmutableError(self._model)
with transaction.atomic():
models.RepositoryContent.objects.filter(version_added=self._model).delete()
models.RepositoryContent.objects.filter(version_removed=self._model)\
.update(version_removed=None)
models.CreatedResource.objects.filter(object_id=self._model.pk).delete()
self._model.repository.last_version = self._model.number - 1
self._model.repository.save()
self._model.delete()
repositories = DetailRelatedField(
view_name_pattern=r"repositories(-.*/.*)-detail",
queryset=models.Repository.objects.all(),
many=True,
)
last_export = ExportRelatedField(
help_text=_("Last attempted export for this PulpExporter"),
queryset=models.PulpExport.objects.all(),
many=False,
required=False,
allow_null=True,
)
class Meta:
model = models.PulpExporter
fields = ExporterSerializer.Meta.fields + ("path", "repositories", "last_export")
class FilesystemExporterSerializer(ExporterSerializer):
"""
Base serializer for FilesystemExporters.
"""
path = serializers.CharField(help_text=_("File system location to export to."))
class Meta:
model = models.FilesystemExporter
fields = ExporterSerializer.Meta.fields + ("path",)
class PublicationExportSerializer(serializers.Serializer):
# pulpcore.serializers is still initializing, so the pulpcore.serializers namespace isn't
# importable. fields loads after base, so bring it in with a relative import
from . import base
class ConfigKeyValueRelatedField(base.GenericKeyValueRelatedField):
help_text = _('A mapping of string keys to string values, for configuring this object.')
required = False
queryset = models.Config.objects.all()
class NotesKeyValueRelatedField(base.GenericKeyValueRelatedField):
help_text = _('A mapping of string keys to string values, for storing notes on this object.')
required = False
queryset = models.Notes.objects.all()
class ScratchpadKeyValueRelatedField(base.GenericKeyValueRelatedField):
help_text = _('A mapping of string keys to string values, for storing an arbitrary information '
'of this object.')
required = False
queryset = models.Scratchpad.objects.all()
RelatedField,
RepositoryVersionRelatedField,
)
from pulpcore.app.util import get_viewset_for_model
class ExporterSerializer(ModelSerializer):
"""
Base serializer for Exporters.
"""
pulp_href = DetailIdentityField(view_name_pattern=r"exporter(-.*/.*)-detail",)
name = serializers.CharField(
help_text=_("Unique name of the file system exporter."),
validators=[UniqueValidator(queryset=models.Exporter.objects.all())],
)
@staticmethod
def validate_path(value, check_is_dir=False):
"""
Check if path is in ALLOWED_EXPORT_PATHS.
Args:
value: The user-provided value path to be validated.
check_is_dir: If true, insure path ends with a directory
Raises:
ValidationError: When path is not in the ALLOWED_EXPORT_PATHS setting.
Returns:
The validated value.
)
class Meta:
model = models.PulpExporter
fields = ExporterSerializer.Meta.fields + ("path", "repositories", "last_export")
class FilesystemExporterSerializer(ExporterSerializer):
"""
Base serializer for FilesystemExporters.
"""
path = serializers.CharField(help_text=_("File system location to export to."))
class Meta:
model = models.FilesystemExporter
fields = ExporterSerializer.Meta.fields + ("path",)
class PublicationExportSerializer(serializers.Serializer):
"""
Serializer for exporting publications.
"""
publication = DetailRelatedField(
required=True,
help_text=_("A URI of the publication to be exported."),
view_name_pattern=r"publications(-.*/.*)-detail",
queryset=models.Publication.objects.all(),
)
required=False
)
notes = GenericKeyValueRelatedField(
help_text=_('A mapping of string keys to string values, for storing notes on this object.'),
required=False
)
publishers = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='publishers-detail'
)
class Meta:
model = models.Consumer
fields = ModelSerializer.Meta.fields + ('name', 'description', 'notes')
match = re.compile(CONTENT_RANGE_PATTERN).match(content_range)
if not match:
raise serializers.ValidationError(_("Invalid or missing content range header."))
data["start"] = start = int(match[1])
end = int(match[2])
if (end - start + 1) != len(data["file"]):
raise serializers.ValidationError(_("Chunk size does not match content range."))
if end > self.context["upload"].size - 1:
raise serializers.ValidationError(_("End byte is greater than upload size."))
return data
class Meta:
model = models.UploadChunk
fields = ("file", "sha256", "offset", "size")
class UploadSerializer(base.ModelSerializer):
"""Serializer for chunked uploads."""
pulp_href = base.IdentityField(view_name="uploads-detail",)
size = serializers.IntegerField(help_text=_("The size of the upload in bytes."))
completed = serializers.DateTimeField(
help_text=_("Timestamp when upload is committed."), read_only=True
)
class Meta:
model = models.Upload