Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove _artifact vs. _artifacts boilerplate #159

Merged
merged 1 commit into from Jan 31, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.rst
Expand Up @@ -149,13 +149,13 @@ Create ``file`` content from an Artifact

Create a content unit and point it to your artifact

``$ http POST http://localhost:8000/pulp/api/v3/content/file/files/ relative_path=foo.tar.gz artifact="/pulp/api/v3/artifacts/1/"``
``$ http POST http://localhost:8000/pulp/api/v3/content/file/files/ relative_path=foo.tar.gz _artifact="/pulp/api/v3/artifacts/1/"``

.. code:: json

{
"_href": "/pulp/api/v3/content/file/files/1/",
"artifact": "/pulp/api/v3/artifacts/1/",
"_artifact": "/pulp/api/v3/artifacts/1/",
"relative_path": "foo.tar.gz",
"type": "file"
}
Expand Down
20 changes: 1 addition & 19 deletions pulp_file/app/models.py
Expand Up @@ -2,7 +2,7 @@

from django.db import models

from pulpcore.plugin.models import Content, ContentArtifact, Remote, Publisher
from pulpcore.plugin.models import Content, Remote, Publisher


log = getLogger(__name__)
Expand All @@ -25,24 +25,6 @@ class FileContent(Content):
relative_path = models.TextField(null=False)
digest = models.TextField(null=False)

@property
def artifact(self):
"""
Return the artifact id (there is only one for this content type).
"""
return self._artifacts.get().pk

@artifact.setter
def artifact(self, artifact):
"""
Set the artifact for this FileContent.
"""
if self.pk:
ca = ContentArtifact(artifact=artifact,
content=self,
relative_path=self.relative_path)
ca.save()

class Meta:
unique_together = (
'relative_path',
Expand Down
25 changes: 9 additions & 16 deletions pulp_file/app/serializers.py
Expand Up @@ -2,47 +2,40 @@

from rest_framework import serializers

from pulpcore.plugin.models import Artifact
from pulpcore.plugin.serializers import (
ContentSerializer,
RelatedField,
SingleArtifactContentSerializer,
RemoteSerializer,
PublisherSerializer
)

from .models import FileContent, FileRemote, FilePublisher


class FileContentSerializer(ContentSerializer):
class FileContentSerializer(SingleArtifactContentSerializer):
"""
Serializer for File Content.
"""

relative_path = serializers.CharField(
help_text="Relative location of the file within the repository"
)
artifact = RelatedField(
view_name='artifacts-detail',
help_text="Artifact file representing the physical content",
queryset=Artifact.objects.all()
)

def validate(self, data):
"""Validate the FileContent data."""
artifact = data['artifact']
artifact = data['_artifact']
content = FileContent.objects.filter(digest=artifact.sha256,
relative_path=data['relative_path'])

if content.exists():
raise serializers.ValidationError(_("There is already a file content with relative "
"path '{path}' and artifact '{artifact}'."
).format(path=data["relative_path"],
artifact=self.initial_data["artifact"]))
raise serializers.ValidationError(_(
"There is already a file content with relative path '{path}' and artifact "
"'{artifact}'."
).format(path=data["relative_path"], artifact=self.initial_data["_artifact"]))

return data

class Meta:
fields = tuple(set(ContentSerializer.Meta.fields) - {'_artifacts'}) + ('relative_path',
'artifact')
fields = SingleArtifactContentSerializer.Meta.fields + ('relative_path',)
model = FileContent


Expand Down
19 changes: 10 additions & 9 deletions pulp_file/app/viewsets.py
@@ -1,12 +1,12 @@
from gettext import gettext as _
from gettext import gettext as _ # noqa

from django.db import transaction
from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import detail_route
from rest_framework import serializers, status
from rest_framework import status
from rest_framework.response import Response

from pulpcore.plugin.models import Artifact
from pulpcore.plugin.models import ContentArtifact
from pulpcore.plugin.serializers import (
AsyncOperationResponseSerializer,
RepositoryPublishURLSerializer,
Expand Down Expand Up @@ -54,16 +54,17 @@ def create(self, request):
"""
Create a new FileContent from a request.
"""
try:
artifact = self.get_resource(request.data['artifact'], Artifact)
except KeyError:
raise serializers.ValidationError(detail={'artifact': _('This field is required')})

serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
artifact = serializer.validated_data.pop('_artifact')
content = serializer.save(digest=artifact.sha256)
content.artifact = artifact

if content.pk:
ContentArtifact.objects.create(
artifact=artifact,
content=content,
relative_path=content.relative_path
)
headers = self.get_success_headers(request.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

Expand Down
2 changes: 1 addition & 1 deletion pulp_file/tests/functional/utils.py
Expand Up @@ -76,7 +76,7 @@ def gen_file_content_attrs(artifact):
:param artifact: A dict of info about the artifact.
:returns: A semi-random dict for use in creating a content unit.
"""
return {'artifact': artifact['_href'], 'relative_path': utils.uuid4()}
return {'_artifact': artifact['_href'], 'relative_path': utils.uuid4()}


def get_file_content_paths(repo, version_href=None):
Expand Down
4 changes: 2 additions & 2 deletions pulp_file/tests/unit/test_serializers.py
Expand Up @@ -23,15 +23,15 @@ def setUp(self):

def test_valid_data(self):
"""Test that the FileContentSerializer accepts valid data."""
data = {"artifact": "/pulp/api/v3/artifacts/{}/".format(self.artifact.pk),
data = {"_artifact": "/pulp/api/v3/artifacts/{}/".format(self.artifact.pk),
"relative_path": "foo"}
serializer = FileContentSerializer(data=data)
self.assertTrue(serializer.is_valid())

def test_duplicate_data(self):
"""Test that the FileContentSerializer does not accept data."""
FileContent.objects.create(relative_path="foo", digest=self.artifact.sha256)
data = {"artifact": "/pulp/api/v3/artifacts/{}/".format(self.artifact.pk),
data = {"_artifact": "/pulp/api/v3/artifacts/{}/".format(self.artifact.pk),
"relative_path": "foo"}
serializer = FileContentSerializer(data=data)
self.assertFalse(serializer.is_valid())