class EditDeleteComment(APIView): """ Edit (PUT) and delete (DELETE) a comment for a given unmapped entry """ permission_class = (IsAuthenticated, ) schema = ManualSchema( description="Edit or delete a comment for a given unmapped entry.", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description= "The mapping_view id associated to the unmapped entry"), coreapi.Field( name="comment_id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the comment"), ]) def put(self, request, mapping_view_id, comment_id): uniprot_entry = get_uniprot_entry(mapping_view_id) if 'text' not in request.data: return Response({'error': 'Text not specified'}, status=status.HTTP_400_BAD_REQUEST) try: comment = uniprot_entry.comments.get(id=comment_id) except UeUnmappedEntryComment.DoesNotExist: return Response( {'error': "Invalid comment ID: {}".format(comment_id)}, status=status.HTTP_400_BAD_REQUEST) else: if comment.deleted: return Response({'error': 'Cannot edit deleted comment'}, status=status.HTTP_400_BAD_REQUEST) comment.comment = request.data['text'] comment.time_stamp = timezone.now() comment.save() serializer = CommentSerializer({ 'commentId': comment.id, 'text': comment.comment, 'timeAdded': comment.time_stamp, 'user': comment.user_stamp.full_name, 'editable': request.user and request.user == comment.user_stamp }) return Response(serializer.data) def delete(self, request, mapping_view_id, comment_id): uniprot_entry = get_uniprot_entry(mapping_view_id) try: comment = uniprot_entry.comments.get(id=comment_id) except: return Response( {'error': "Invalid comment ID: {}".format(comment_id)}, status=status.HTTP_400_BAD_REQUEST) else: comment.deleted = True comment.save() return Response(status=status.HTTP_204_NO_CONTENT)
class AddDeleteLabel(APIView): """ Add or delete label a associated to the given unmapped entry """ permission_classes = (IsAuthenticated, ) schema = ManualSchema( description= "Add or delete label a associated to the given unmapped entry", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description= "The mapping view id associated to the unmapped entry"), coreapi.Field( name="label_id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the label"), ]) def post(self, request, mapping_view_id, label_id): uniprot_entry = get_uniprot_entry(mapping_view_id) entry_labels = UeUnmappedEntryLabel.objects.filter( uniprot=uniprot_entry, label=label_id) if entry_labels: # label already attached, ignore return Response(status=status.HTTP_204_NO_CONTENT) try: serializer = UnmappedEntryLabelSerializer( data={ 'time_stamp': timezone.now(), 'user_stamp': request.user, 'label': label_id, 'uniprot': uniprot_entry.uniprot_id }) except KeyError: raise Http404("Must provide valid label") if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, mapping_view_id, label_id): uniprot_entry = get_uniprot_entry(mapping_view_id) # delete all labels with the given description attached to the mapping # TODO: only those associated to the given user entry_labels = UeUnmappedEntryLabel.objects.filter( uniprot=uniprot_entry, label=label_id) if entry_labels: entry_labels.delete() return Response(status=status.HTTP_204_NO_CONTENT) raise Http404
class AddGetComments(APIView): """ Add a comment/Retrieve all comments relative to a given unmapped entry """ permission_classes = (IsAuthenticated, ) schema = ManualSchema( description= "Add a comment/Retrieve all comments relative to a given unmapped entry.", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description= "The mapping view id associated to the unmapped entry"), ]) def get(self, request, mapping_view_id): uniprot_entry = get_uniprot_entry(mapping_view_id) # fetch mapping comment history, exclude deleted comments entry_comments = uniprot_entry.comments.filter( deleted=False).order_by('-time_stamp') # comments are editable if they belong to the requesting user comments = map( lambda c: { 'commentId': c.id, 'text': c.comment, 'timeAdded': c.time_stamp, 'user': c.user_stamp.full_name, 'editable': request.user and request.user == c.user_stamp }, entry_comments) data = {'mapping_view_id': mapping_view_id, 'comments': list(comments)} serializer = UnmappedEntryCommentsSerializer(data) return Response(serializer.data) def post(self, request, mapping_view_id): uniprot_entry = get_uniprot_entry(mapping_view_id) try: serializer = UnmappedEntryCommentSerializer( data={ 'time_stamp': timezone.now(), 'user_stamp': request.user, 'comment': request.data['text'], 'uniprot': uniprot_entry.uniprot_id, 'deleted': False }) except KeyError: raise Http404("Must provide comment") if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes, action from rest_apis.api.serializers import Registeruser from rest_framework.authtoken.models import Token from django.contrib.auth import logout, login, authenticate from rest_framework.permissions import IsAuthenticated from rest_apis.models import userinfo from rest_framework.schemas import ManualSchema from rest_framework.compat import coreapi, coreschema custom_schema = ManualSchema(fields=[ coreapi.Field("first_field", required=True, location="path", schema=coreschema.String()), coreapi.Field("second_field", required=True, location="path", schema=coreschema.String()), ]) @api_view(["POST"]) @permission_classes([permissions.AllowAny]) @action(schema=custom_schema, detail=True) def api_register_user(request): serial = Registeruser(data=request.data) data = {} new_list = [] if serial.is_valid(): new_user = serial.save()
class UnmappedEntries(APIView): """ Present the details for Swissprot/Ensembl unmapped entities for the latest release for a given species """ # pagination_class = PageNumberPagination # settings.DEFAULT_PAGINATION_CLASS schema = ManualSchema( description= ("Present the details for Swissprot/Ensembl unmapped entities for the " "latest release for a given species"), fields=[ coreapi.Field(name="taxid", required=True, location="path", schema=coreschema.Integer(), description="Taxonomy id"), coreapi.Field( name="source", required=True, location="path", schema=coreschema.String(), description="Source, either 'swissprot' or 'ensembl'"), ]) def get(self, request, taxid, source): if source == 'swissprot': # the Swissprot entries: # uniprot_entry_history for release X minus mapping_history for release X # = all unmapped uniprot entries for release X # that all can be filtered by entry type # find the latest uniprot release corresponding to the species release_mapping_history = ReleaseMappingHistory.objects.filter( uniprot_taxid=taxid).latest('release_mapping_history_id') # get the Uniprot entries corresponding to that species and uniprot release release_uniprot_entries = UniprotEntry.objects.select_related( 'entry_type' ).filter( uniprot_tax_id=taxid, uniprotentryhistory__release_version=release_mapping_history. uniprot_release, entry_type__description__icontains='swiss') # find the mapped uniprot entries for the release and species release_mapped_uniprot_entries = UniprotEntry.objects.select_related( 'entry_type').filter( mapping__mapping_history__release_mapping_history= release_mapping_history, entry_type__description__icontains='swiss').distinct() # the unmapped swiss-prot entries # NOTE: using select_related('entry_type') to speed up query # generates 'Index out of range' error, using it in the two sets # above works release_unmapped_sp_entries = release_uniprot_entries.difference( release_mapped_uniprot_entries) data = list( map( lambda ue: { 'uniprotAccession': ue.uniprot_acc, "entryType": ue.entry_type.description, "isCanonical": not ue.canonical_uniprot_id, "alias": ue.alias if ue.alias else None, "gene_symbol": ue.gene_symbol, "gene_accession": ue.chromosome_line, "length": ue.length, "protein_existence_id": ue.protein_existence_id }, release_unmapped_sp_entries.order_by('uniprot_acc'))) page = self.paginate_queryset(data) if page is not None: serializer = UnmappedSwissprotEntrySerializer(page, many=True) return self.get_paginated_response(serializer.data) # if pagination is not defined serializer = UnmappedSwissprotEntrySerializer(data, many=True) return Response(serializer.data, status=status.HTTP_200_OK) if source == 'ensembl': release_mapping_history = ReleaseMappingHistory.objects.filter( ensembl_species_history__ensembl_tax_id=taxid).latest( 'release_mapping_history_id') release_mapped_transcripts = EnsemblTranscript.objects.select_related( 'gene').filter( mapping__mapping_history__release_mapping_history= release_mapping_history).distinct() """ certain SQL operations, e.g. values(), count(), order_by, don't work on union/intersection/difference see https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.union """ release_unmapped_transcripts = EnsemblTranscript.objects.exclude( transcript_id__in=release_mapped_transcripts.values_list( 'transcript_id', flat=True)) page = self.paginate_queryset(release_unmapped_transcripts) if page is not None: serializer = UnmappedEnsemblEntrySerializer(page, many=True) return self.get_paginated_response(serializer.data) # if pagination is not defined serializer = UnmappedEnsemblEntrySerializer(data, many=True) return Response(serializer.data, status=status.HTTP_200_OK) raise Http404('Unknown source') @property def paginator(self): """ The paginator instance associated with the view, or `None`. """ if not hasattr(self, '_paginator'): source = self.kwargs['source'] if source == 'ensembl': self._paginator = UnmappedEnsemblEntryPagination() # pylint: disable=attribute-defined-outside-init elif source == 'swissprot': self._paginator = LimitOffsetPagination() # pylint: disable=attribute-defined-outside-init else: raise Exception('Unknown source') return self._paginator def paginate_queryset(self, queryset): """ Return a single page of results, or `None` if pagination is disabled. """ if self.paginator is None: return None return self.paginator.paginate_queryset(queryset, self.request, view=self) def get_paginated_response(self, data): """ Return a paginated style `Response` object for the given output data. """ assert self.paginator is not None return self.paginator.get_paginated_response(data)
import coreapi import coreschema from rest_framework.schemas import ManualSchema LoginSchema = ManualSchema(fields=[ coreapi.Field( 'username', required=True, location="body", schema=coreschema.String()), coreapi.Field( 'password', required=True, location="body", schema=coreschema.String()), ])
import coreapi, coreschema from rest_framework.schemas import AutoSchema, ManualSchema addArchitectureSwagger = ManualSchema(fields=[ coreapi.Field(name="projectID", required=True, location="formData", type="string", description="project ID here"), coreapi.Field(name="filePath", required=True, location="formData", type="string", description="path of the pmml") ], encoding="application/json") updateLayerSwagger = ManualSchema(fields=[ coreapi.Field(name="projectID", required=True, location="form", type="string", description="projectID here"), coreapi.Field(name="layerToUpdate", required=True, type="object", location="form", description="layer here") ], encoding="application/json")
journeys_by_time_and_stop_schema = ManualSchema( fields=[ coreapi.Field( "stop_id", required=True, location="query", schema=coreschema.String(description="Stop atco_code " "(e.g. '0500CCITY111')"), description="Stop atco_code (e.g. '0500CCITY111')", example='0500CCITY111', ), coreapi.Field( "datetime_from", required=False, location="query", schema=coreschema.String( description="Start datetime or time for returned results. " "If time is given insetad of a datetime, " "today is used as date. Defaults to now. " "YYYY-MM-DDTHH:MM:SS or HH:MM:SS " "(e.g. '2018-06-01T12:00:00')"), description="Start datetime or time for returned results. " "If time is given insetad of a datetime, " "today is used as date. Defaults to now. " "YYYY-MM-DDTHH:MM:SS or HH:MM:SS " "(e.g. '2018-06-01T12:00:00')", example="2018-06-01T12:00:00", ), coreapi.Field( "nresults", required=False, location="query", schema=coreschema.Integer( description="Maximum number of journeys to return, default " "10. (e.g. 20)"), description="Maximum number of journeys to return, default 10. " "(e.g. 20)", example="20", ), coreapi.Field( "expand_journey", required=False, location="query", schema=coreschema.Boolean( description="Expands the resulting journey into a full " "journey object"), description="Expands the resulting journey into a full " "journey object", ), ], description="Return the timetabled vehicle journeys expected for a given " "stop identified by _stop_id_ from a specific date and time " "identified by _datetime_from_ (optional, default = now). " "\n\n" "All results are paginated based on _nresults_ and a _next_ " "attribute is returned containing the URL to use to retrieve " "more results. The pagination can return up to _nresults_ " "or less if there are no more results for a day, for example.")
class MappingStatusView(APIView): """ Change the status of a mapping """ permission_classes = (IsAuthenticated, ) schema = ManualSchema( description="Change the status of a mapping", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the mapping"), ]) def put(self, request, pk): mapping = get_mapping(pk) # retrieve the status object associated to the given description try: s = CvUeStatus.objects.get(description=request.data['status']) except KeyError: raise Http404("Payload should have 'status'") except CvUeStatus.DoesNotExist: raise Http404("Couldn't get status object for {}".format( request.data['status'])) except MultipleObjectsReturned: raise Http404("Couldn't get unique status for {}".format( request.data['status'])) """ If the mapping has already been assigned that status, update the timestamp, otherwise create one from scratch """ try: mapping_status = UeMappingStatus.objects.filter( mapping=mapping).latest('time_stamp') except UeMappingStatus.DoesNotExist: # It's alright, for the first status change of a mapping a # historic record won't exist. pass else: if mapping_status.status.id == s.id: # The user is trying to change it to what the status # already is, nothing to do. return Response(status=status.HTTP_204_NO_CONTENT) # create new mapping status serializer = MappingStatusSerializer( data={ 'time_stamp': timezone.now(), 'user_stamp': request.user, 'status': s.id, 'mapping': mapping.mapping_id }) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Update the status in the mapping record mapping.status = s mapping.save() # update status on mapping_view corresponding entry, # otherwise search won't reflect the status change try: mv = MappingView.objects.get(mapping_id=pk) except MappingView.DoesNotExist: return Response( { "error": "Could not find mapping {} in search table.".format(pk) }, status=status.HTTP_400_BAD_REQUEST) else: mv.status = s.id mv.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
class MappingCommentsView(APIView): """ Add a comment/Retrieve all comments relative to a given mapping, includes mapping labels. """ permission_classes = (IsAuthenticated, ) schema = ManualSchema( description=( "Add a comment/Retrieve all comments relative to a given mapping, " "includes mapping labels."), fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the mapping"), ]) def get(self, request, pk): mapping = get_mapping(pk) # fetch mapping comment history, exclude deleted comments mapping_comments = mapping.comments.filter( deleted=False).order_by('-time_stamp') # comments are editable if they belong to the requesting user comments = [] for comment in mapping_comments: comments.append({ 'commentId': comment.id, 'text': comment.comment, 'timeAdded': comment.time_stamp, 'user': comment.user_stamp.full_name, 'editable': request.user and request.user == comment.user_stamp }) data = {'mappingId': pk, 'comments': comments} serializer = MappingCommentsSerializer(data) return Response(serializer.data) def post(self, request, pk): mapping = get_mapping(pk) try: serializer = MappingCommentSerializer( data={ 'time_stamp': timezone.now(), 'user_stamp': request.user, 'comment': request.data['text'], 'mapping': mapping.mapping_id, 'deleted': False }) except KeyError: raise Http404("Must provide comment") if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class EditDeleteCommentView(APIView): """ Edit (PUT) and delete (DELETE) a comment for a given mapping. """ permission_class = (IsAuthenticated, ) schema = ManualSchema( description="Edit or delete a comment for a given mapping.", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the mapping"), coreapi.Field( name="comment_id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the comment"), ]) def put(self, request, pk, comment_id): mapping = get_mapping(pk) if 'text' not in request.data: return Response({"error": "Text not specified"}, status=status.HTTP_400_BAD_REQUEST) try: comment = mapping.comments.get(id=comment_id) except UeMappingComment.DoesNotExist: return Response( {"error": "Invalid comment ID: {}".format(comment_id)}, status=status.HTTP_400_BAD_REQUEST) else: if comment.deleted: return Response({"error": "Cannot edit deleted comment"}, status=status.HTTP_400_BAD_REQUEST) comment.comment = request.data['text'] comment.time_stamp = timezone.now() comment.save() editable = False if request.user and request.user == comment.user_stamp: editable = True serializer = CommentLabelSerializer({ 'commentId': comment.id, 'text': comment.comment, 'timeAdded': comment.time_stamp, 'user': comment.user_stamp.full_name, 'editable': editable }) return Response(serializer.data) def delete(self, request, pk, comment_id): mapping = get_mapping(pk) try: comment = mapping.comments.get(id=comment_id) except: return Response( {"error": "Invalid comment ID: {}".format(comment_id)}, status=status.HTTP_400_BAD_REQUEST) else: comment.deleted = True comment.save() return Response(status=status.HTTP_204_NO_CONTENT)
class MappingLabelView(APIView): """ Add or delete label a associated to the given mapping """ permission_classes = (IsAuthenticated, ) schema = ManualSchema( description="Add or delete label a associated to the given mapping", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the mapping"), coreapi.Field( name="label_id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the label"), ]) def post(self, request, pk, label_id): mapping = get_mapping(pk) mapping_labels = UeMappingLabel.objects.filter(mapping=mapping, label=label_id) if mapping_labels: # mapping already has a label, ignore return Response(status=status.HTTP_204_NO_CONTENT) try: serializer = MappingLabelSerializer( data={ 'time_stamp': timezone.now(), 'user_stamp': request.user, 'label': label_id, 'mapping': pk }) except KeyError: raise Http404("Must provide valid label") if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, label_id): mapping = get_mapping(pk) # delete all labels with the given description attached to the mapping # TODO: only those associated to the given user mapping_labels = UeMappingLabel.objects.filter(mapping=mapping, label=label_id) if mapping_labels: mapping_labels.delete() return Response(status=status.HTTP_204_NO_CONTENT) raise Http404