Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from resolwe.flow.filters import EntityFilter
from resolwe.flow.models import Collection, DescriptorSchema, Entity
from resolwe.flow.serializers import EntitySerializer
from resolwe.permissions.shortcuts import get_objects_for_user
from resolwe.permissions.utils import update_permission
from .collection import BaseCollectionViewSet
from .utils import get_collection_for_user
class EntityViewSet(BaseCollectionViewSet):
"""API view for entities."""
qs_collection_ds = DescriptorSchema.objects.select_related("contributor")
qs_collection = Collection.objects.select_related("contributor")
qs_collection = qs_collection.prefetch_related(
"data", "entity_set", Prefetch("descriptor_schema", queryset=qs_collection_ds),
)
qs_descriptor_schema = DescriptorSchema.objects.select_related("contributor")
queryset = Entity.objects.select_related("contributor").prefetch_related(
"data",
Prefetch("collection", queryset=qs_collection),
Prefetch("descriptor_schema", queryset=qs_descriptor_schema),
)
serializer_class = EntitySerializer
filter_class = EntityFilter
def _get_entities(self, user, ids):
"""Return entities queryset based on provided entity ids."""
"""Serializer for Data objects."""
input = ProjectableJSONField(required=False)
output = ProjectableJSONField(required=False)
descriptor = ProjectableJSONField(required=False)
process = DictRelatedField(
queryset=Process.objects.all(), serializer=ProcessSerializer
)
descriptor_schema = DictRelatedField(
queryset=DescriptorSchema.objects.all(),
serializer=DescriptorSchemaSerializer,
allow_null=True,
required=False,
)
collection = DictRelatedField(
queryset=Collection.objects.all(),
serializer=CollectionSerializer,
allow_null=True,
required=False,
write_permission="edit",
)
entity = DictRelatedField(
queryset=Entity.objects.all(),
serializer=EntitySerializer,
allow_null=True,
required=False,
write_permission="edit",
)
class Meta:
"""DataSerializer Meta options."""
elif isinstance(current, (int, bool, float, str)):
descriptor.append(str(current))
flatten(obj.descriptor)
return descriptor
def get_descriptor_data_value(self, obj):
"""Extract data from the descriptors."""
return self.extract_descriptor(obj)
class CollectionIndex(BaseIndexMixin, CollectionIndexMixin, BaseIndex):
"""Index for collection objects used in ``CollectionDocument``."""
queryset = Collection.objects.all().prefetch_related(
"descriptor_schema", "contributor"
)
object_type = Collection
document_class = CollectionDocument
def duplicate(self, request, *args, **kwargs):
"""Duplicate (make copy of) ``Collection`` models."""
if not request.user.is_authenticated:
raise exceptions.NotFound
ids = self.get_ids(request.data)
queryset = get_objects_for_user(
request.user, "view_collection", Collection.objects.filter(id__in=ids)
)
actual_ids = queryset.values_list("id", flat=True)
missing_ids = list(set(ids) - set(actual_ids))
if missing_ids:
raise exceptions.ParseError(
"Collections with the following ids not found: {}".format(
", ".join(map(str, missing_ids))
)
)
duplicated = queryset.duplicate(contributor=request.user)
serializer = self.get_serializer(duplicated, many=True)
return Response(serializer.data)
"""Resolwe entity serializer."""
from resolwe.flow.models import Collection, Entity
from .collection import BaseCollectionSerializer
from .fields import DictRelatedField
class EntitySerializer(BaseCollectionSerializer):
"""Serializer for Entity."""
collection = DictRelatedField(
queryset=Collection.objects.all(),
serializer=BaseCollectionSerializer,
allow_null=True,
required=False,
write_permission="edit",
)
class Meta(BaseCollectionSerializer.Meta):
"""EntitySerializer Meta options."""
model = Entity
fields = BaseCollectionSerializer.Meta.fields + (
"collection",
"duplicated",
"type",
)
"entity__slug": SLUG_LOOKUPS[:],
"process": RELATED_LOOKUPS[:],
"process__name": TEXT_LOOKUPS[:],
"process__slug": SLUG_LOOKUPS[:],
"finished": DATETIME_LOOKUPS[:],
"started": DATETIME_LOOKUPS[:],
"status": ["exact", "in"],
},
}
class RelationFilter(BaseResolweFilter):
"""Filter the Relation endpoint."""
category = filters.CharFilter(lookup_expr="iexact")
collection = filters.ModelChoiceFilter(queryset=Collection.objects.all())
type = filters.CharFilter(field_name="type__name")
class Meta(BaseResolweFilter.Meta):
"""Filter configuration."""
model = Relation
fields = BaseResolweFilter.Meta.fields
def get_always_allowed_arguments(self):
"""Get always allowed query arguments."""
return super().get_always_allowed_arguments() + ("entity", "label", "position",)
class OrderingFilter(DrfOrderingFilter):
"""Order results by field specified in request.
"""Serializer for PositionInRelation objects."""
position = ProjectableJSONField(allow_null=True, required=False)
class Meta:
"""PositionInRelationSerializer Meta options."""
model = PositionInRelation
fields = ('entity', 'position')
class RelationSerializer(ResolweBaseSerializer):
"""Serializer for Relation objects."""
entities = PositionInRelationSerializer(source='positioninrelation_set', many=True)
collection = serializers.PrimaryKeyRelatedField(queryset=Collection.objects.all(), required=True)
class Meta:
"""RelationSerializer Meta options."""
model = Relation
update_protected_fields = ('contributor', 'entities', 'type')
read_only_fields = ('id', 'created', 'modified')
fields = ('collection', 'entities', 'label') + update_protected_fields + read_only_fields
def get_fields(self):
"""Dynamically adapt fields based on the current request."""
fields = super().get_fields()
if self.request.method == "GET":
fields['type'] = serializers.CharField(source='type.name')
else:
def add_to_collection(self, request, pk=None):
"""Add Entity to a collection."""
entity = self.get_object()
if 'ids' not in request.data:
return Response({"error": "`ids` parameter is required"}, status=status.HTTP_400_BAD_REQUEST)
for collection_id in request.data['ids']:
self._check_collection_permissions(collection_id, request.user)
for collection_id in request.data['ids']:
entity.collections.add(collection_id)
collection = Collection.objects.get(pk=collection_id)
for data in entity.data.all():
collection.data.add(data)
return Response()
class DataViewSet(
ResolweCreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
ResolweUpdateModelMixin,
mixins.DestroyModelMixin,
ResolwePermissionsMixin,
ResolweCheckSlugMixin,
ParametersMixin,
viewsets.GenericViewSet,
):
"""API view for :class:`Data` objects."""
qs_collection_ds = DescriptorSchema.objects.select_related("contributor")
qs_collection = Collection.objects.select_related("contributor")
qs_collection = qs_collection.prefetch_related(
"data", "entity_set", Prefetch("descriptor_schema", queryset=qs_collection_ds),
)
qs_descriptor_schema = DescriptorSchema.objects.select_related("contributor")
qs_entity_col_ds = DescriptorSchema.objects.select_related("contributor")
qs_entity_col = Collection.objects.select_related("contributor")
qs_entity_col = qs_entity_col.prefetch_related(
"data", "entity_set", Prefetch("descriptor_schema", queryset=qs_entity_col_ds),
)
qs_entity_ds = DescriptorSchema.objects.select_related("contributor")
qs_entity = Entity.objects.select_related("contributor")
qs_entity = qs_entity.prefetch_related(
"data",
Prefetch("collection", queryset=qs_entity_col),
def perform_create(self, serializer):
"""Create a resource."""
with transaction.atomic():
instance = serializer.save()
# Assign all permissions to the object contributor.
for permission in list(zip(*instance._meta.permissions))[0]: # pylint: disable=protected-access
assign_perm(permission, instance.contributor, instance)
# Assign data object to all specified collections.
collections = self.request.data.get('collections', [])
for c in collections:
collection = Collection.objects.get(pk=c)
collection.data.add(instance)