Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def create(self, request, *args, **kwargs):
"""Create a resource."""
collections = request.data.get('collections', [])
# check that user has permissions on all collections that Data
# object will be added to
for collection_id in collections:
try:
collection = Collection.objects.get(pk=collection_id)
except Collection.DoesNotExist:
return Response({'collections': ['Invalid pk "{}" - object does not exist.'.format(collection_id)]},
status=status.HTTP_400_BAD_REQUEST)
if not request.user.has_perm('add_collection', obj=collection):
if request.user.is_authenticated():
raise exceptions.PermissionDenied
else:
raise exceptions.NotFound
# translate processe's slug to id
process_slug = request.data.get('process', None)
process_query = Process.objects.filter(slug=process_slug)
process_query = get_objects_for_user(request.user, 'view_process', process_query)
try:
process = process_query.latest()
except Process.DoesNotExist:
def create(self, request, *args, **kwargs):
"""Create a resource."""
collections = request.data.get('collections', [])
# check that user has permissions on all collections that Data
# object will be added to
for collection_id in collections:
try:
collection = Collection.objects.get(pk=collection_id)
except Collection.DoesNotExist:
return Response({'collections': ['Invalid pk "{}" - object does not exist.'.format(collection_id)]},
status=status.HTTP_400_BAD_REQUEST)
if not request.user.has_perm('add_collection', obj=collection):
if request.user.is_authenticated():
raise exceptions.PermissionDenied
else:
raise exceptions.NotFound
# translate processe's slug to id
process_slug = request.data.get('process', None)
process_query = Process.objects.filter(slug=process_slug)
process_query = get_objects_for_user(request.user, 'view_process', process_query)
try:
process = process_query.latest()
"""Postgres model for storing entities."""
class Meta(BaseCollection.Meta):
"""Entity Meta options."""
permissions = (
("view_entity", "Can view entity"),
("edit_entity", "Can edit entity"),
("share_entity", "Can share entity"),
("download_entity", "Can download files from entity"),
("add_entity", "Can add data objects to entity"),
("owner_entity", "Is owner of the entity"),
)
#: list of collections to which entity belongs
collections = models.ManyToManyField(Collection)
def iterate_fields(fields, schema, path_prefix=None):
"""Iterate over all field values sub-fields.
This will iterate over all field values. Some fields defined in the schema
might not be visited.
:param fields: field values to iterate over
:type fields: dict
:param schema: schema to iterate over
:type schema: dict
:return: (field schema, field value)
:rtype: tuple
"""
def clear_database(self):
"""Clear data base."""
for model in [Collection, Data, Process, Storage, DescriptorSchema,
GroupObjectPermission, UserObjectPermission]:
model.objects.all().delete()
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),
Prefetch("descriptor_schema", queryset=qs_entity_ds),
)
qs_process = Process.objects.select_related("contributor")
queryset = Data.objects.select_related("contributor").prefetch_related(
Prefetch("collection", queryset=qs_collection),
Prefetch("descriptor_schema", queryset=qs_descriptor_schema),
new.started = data[u'date_start']
new.finished = data[u'date_finish']
elif u'date_finish' in data:
new.started = data[u'date_finish']
new.finished = data[u'date_finish']
elif u'date_start' in data:
new.started = data[u'date_start']
new.finished = data[u'date_start']
else:
new.started = datetime.fromtimestamp(0)
new.finished = datetime.fromtimestamp(0)
new.save()
for case_id in data[u'case_ids']:
try:
collection = Collection.objects.get(pk=self.id_mapping[u'collection'][str(case_id)])
except KeyError:
self.missing_collections.add(str(case_id))
continue
collection.data.add(new)
for field_schema, fields, path in iterate_fields(data[u'output'], data[u'output_schema'], ''):
if 'type' in field_schema and field_schema['type'].startswith('basic:json:'):
self.storage_index[fields[field_schema['name']]] = {
'id': new.pk,
'path': path,
}
self.migrate_permissions(new, data)
self.id_mapping['data'][str(data[u'_id'])] = new.pk
class BaseCollectionViewSet(
ResolweCreateModelMixin,
mixins.RetrieveModelMixin,
ResolweUpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
ResolwePermissionsMixin,
ResolweCheckSlugMixin,
ParametersMixin,
viewsets.GenericViewSet,
):
"""Base API view for :class:`Collection` objects."""
qs_descriptor_schema = DescriptorSchema.objects.select_related("contributor")
queryset = Collection.objects.select_related("contributor").prefetch_related(
Prefetch("descriptor_schema", queryset=qs_descriptor_schema),
)
filter_class = CollectionFilter
permission_classes = (get_permissions_class(),)
ordering_fields = (
"contributor",
"contributor__first_name",
"contributor__last_name",
"created",
"id",
"modified",
"name",
)
ordering = "id"