class ObtainAuthToken(APIView): throttle_classes = () permission_classes = () parser_classes = ( parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser, ) renderer_classes = (renderers.JSONRenderer, ) serializer_class = AuthTokenSerializer if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="username", required=True, location='form', schema=coreschema.String( title="Username", description="Valid username for authentication", ), ), coreapi.Field( name="password", required=True, location='form', schema=coreschema.String( title="Password", description="Valid password for authentication", ), ), ], encoding="application/json", )
class CustomAuthToken(ObtainAuthToken): serializer_class = CustomAuthTokenSerializer if coreapi_schema.is_enabled(): schema = ManualSchema( fields=[ coreapi.Field( name="email", required=True, location='form', schema=coreschema.String( title="Email", description="Valid email for authentication", ), ), coreapi.Field( name="password", required=True, location='form', schema=coreschema.String( title="Password", description="Valid password for authentication", ), ), ], encoding="application/json", )
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': True if request.user and request.user == comment.user_stamp else False }) 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("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 MobileRegisterToken(APIView): serializer_class = MobileAuthTokenRegisterSerializer if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name='uuid', required=True, location='form', schema=coreschema.String( title='Device UUID', description='Valid device UUID for authentication', ), ), ], encoding='application/json', ) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) uuid = serializer.validated_data['uuid'] device_token = DeviceKey.objects.get_or_create_token(uuid=uuid, user=request.user)[0] return Response({'device_login_token': device_token})
class LatestEnsemblRelease(APIView): """ Fetch the latest Ensembl release whose load is complete. """ schema = ManualSchema( description="Fetch the latest Ensembl release whose load is complete", fields=[ coreapi.Field(name="assembly_accession", required=True, location="path", schema=coreschema.String(), description="Assembly accession") ]) def get(self, request, assembly_accession): try: species_history = EnsemblSpeciesHistory.objects.filter( assembly_accession__iexact=assembly_accession, status='LOAD_COMPLETE').latest('ensembl_release') except (EnsemblSpeciesHistory.DoesNotExist, IndexError): raise Http404 serializer = EnsemblReleaseSerializer( {'release': species_history.ensembl_release}) return Response(serializer.data)
class VerifyViewSet(viewsets.ViewSet): """Resource to handle the verification of an user's email.""" schema = ManualSchema( encoding="application/json", fields=[ coreapi.Field( "verification_code", required=True, location="body", schema=coreschema.String( description=_("Verification code for the user.") ), ) ], ) def create(self, request): serializer = VerifySerializer(data=request.data) if serializer.is_valid(): verification_code = serializer.validated_data["verification_code"] verify_email(verification_code) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class AdminAuthToken(ObtainAuthToken): permission_classes = (OrganizationUserAdminPermission,) serializer_class = UserTokenSerializer if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="email", required=True, location="form", schema=coreschema.String(title="Email", description="Valid email",), ), ], encoding="application/json", ) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] self.check_object_permissions(request, user) token, created = Token.objects.get_or_create(user=user) return Response( { "token": token.key, "id": user.id, "client_id": user.client.id, "client_name": user.client.name, "email": user.email, } )
class CustomObtainAuthToken(views.ObtainAuthToken): serializer_class = serializers.CustomAuthTokenSerializer if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="email", required=True, location='form', schema=coreschema.String( title="Email", description="Valid email for authentication", ), ), coreapi.Field( name="password", required=True, location='form', schema=coreschema.String( title="Password", description="Valid password for authentication", ), ), ], encoding="application/json", ) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key, 'user_id': user.id})
class MappingsByHistory(generics.ListAPIView): """ Fetch mappings corresponding to a given release mapping history """ serializer_class = MappingByHistorySerializer pagination_class = PageNumberPagination schema = ManualSchema( description= "Fetch mappings corresponding to a given release mapping history", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description= "A unique integer value identifying this release mapping history." ), ]) def get_queryset(self): release_mapping_history_id = self.kwargs['pk'] try: return Mapping.objects.filter( mapping_history__release_mapping_history= release_mapping_history_id).order_by('mapping_id') except Mapping.DoesNotExist: raise Http404
class AlignmentByAlignmentRunFetch(generics.ListAPIView): """ Retrieve all alignments for a given alignment run """ serializer_class = AlignmentSerializer pagination_class = PageNumberPagination schema = ManualSchema( description="Retrieve all alignments for a given alignment run", fields=[ coreapi.Field(name="id", required=True, location="path", schema=coreschema.Integer(), description="Alignmet run id") ]) def get_queryset(self): try: alignment_run = AlignmentRun.objects.get(pk=self.kwargs["pk"]) except (AlignmentRun.DoesNotExist, IndexError): raise Http404 return Alignment.objects.filter( alignment_run=alignment_run).order_by('alignment_id')
class EnspUCigarFetchUpdateByAlignment(generics.RetrieveUpdateAPIView): """ Fetch/Update cigar/mdz by alignment id """ serializer_class = EnspUCigarSerializer schema = ManualSchema(description="Fetch/Update cigar/mdz by alignment id", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description="Alignmet id" ), ]) def get_object(self): try: obj = EnspUCigar.objects.get(alignment=self.kwargs['pk']) except: raise Http404 self.check_object_permissions(self.request, obj) return obj
class CustomAuthToken(ObtainAuthToken): """View for custom auth token""" serializer_class = CustomAuthTokenSerializer if coreapi_schema.is_enabled(): schema = ManualSchema( fields=[ coreapi.Field( name="email", required=True, location='form', schema=coreschema.String( title="Email", description="Valid email for authentication", ), ), coreapi.Field( name="password", required=True, location='form', schema=coreschema.String( title="Password", description="Valid password for authentication", ), ), ], encoding="application/json", ) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key, 'user_id': user.id})
class AlignmentByAlignmentRunFetch(generics.ListAPIView): """ Retrieve all alignments for a given alignment run """ serializer_class = AlignmentSerializer pagination_class = LongResultsPagination schema = ManualSchema( description="Retrieve all alignments for a given alignment run", fields=[ coreapi.Field(name="id", required=True, location="path", schema=coreschema.Integer(), description="Alignmet run id") ]) def get_queryset(self): try: alignment_run = AlignmentRun.objects.get(pk=self.kwargs["pk"]) except (AlignmentRun.DoesNotExist, IndexError): raise Http404 mapping_ids = self.request.query_params.get('mapping_id', None) if mapping_ids is not None: mapping_ids = mapping_ids.split(',') return Alignment.objects.filter(alignment_run=alignment_run, mapping_id__in=mapping_ids) else: return Alignment.objects.filter( alignment_run=alignment_run).order_by('alignment_id')
class AddressView(GenericViewSet): permission_classes = (AllowAny,) queryset = Address.objects.all() def get_serializer_class(self): serializer_class = get_generic_read_serializer(Address, 1) return serializer_class @action( methods=["get"], detail=False, url_path="findbyzip", schema=ManualSchema( description="Gets an address by zip code", fields=[ coreapi.Field( "zip", required=True, location="query", schema=coreschema.String(), description="Zip code", ) ], ), ) def find_address_by_zip(self, request: Request): zip_code = get_param_or_400(request.query_params, "zip", str) if len(zip_code) != 8: raise ValueError(_("Zip code length should have exactly 8")) result_dict = { "city": {"id": None, "description": None}, "zip": None, "neighborhood": {"id": None, "description": None}, "state": {"id": None, "description": None, "initials": None}, "address": None, } try: address = Address.get_by_zip(zip_code) except Address.DoesNotExist: address = None if address: result_dict["city"]["id"] = address.neighborhood.city.id result_dict["city"]["description"] = address.neighborhood.city.description result_dict["zip"] = address.zip_code result_dict["neighborhood"]["id"] = address.neighborhood.id result_dict["neighborhood"][ "description" ] = address.neighborhood.description result_dict["state"]["id"] = address.neighborhood.city.state.id result_dict["state"][ "description" ] = address.neighborhood.city.state.description result_dict["state"]["initials"] = address.neighborhood.city.state.initials result_dict["address"] = address.description return Response(data=result_dict)
class TimeEntrySignoffViewSet(viewsets.ViewSet): schema = ManualSchema(fields=[ coreapi.Field('date', required=True, location='form', schema=coreschema.String()), coreapi.Field('user', required=True, location='form', schema=coreschema.Integer()), ], description='Signoff a users timesheet for a day.') serializer_class = TimeEntrySignoffSerializer def signoff(self, serializer): data = serializer.validated_data entries = TimeEntry.objects.filter(started_at__date=data['date'], user=data['user'], signed_off=False) entry_pks = [e.pk for e in entries] entries.update(signed_off=True) updates_entries = TimeEntry.objects.filter(pk__in=entry_pks) serializer = TimeEntrySerializer(instance=updates_entries, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return self.signoff(serializer)
class ReleasePerSpecies(APIView): """ Retrieve Ensembl/Uniprot release per species """ schema = ManualSchema( description="Retrieve Ensembl/Uniprot release per species", fields=[ coreapi.Field(name="taxid", required=True, location="path", schema=coreschema.Integer(), description="Taxonomy id"), ]) def get(self, request, taxid): # find the latest uniprot release corresponding to the species release_mapping_history = ReleaseMappingHistory.objects.select_related( 'ensembl_species_history').filter( uniprot_taxid=taxid).latest('release_mapping_history_id') serializer = ReleasePerSpeciesSerializer({ 'ensembl': release_mapping_history.ensembl_species_history.ensembl_release, 'uniprot': release_mapping_history.uniprot_release }) return Response(serializer.data)
class ObtainPasswordToken(APIView): throttle_classes = () serializer_class = PasswordTokenSerializer if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="email", required=True, location='form', schema=coreschema.String( title="Email", description="Valid email for password reset", ), ), ], encoding="application/json", ) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['email'] token, created = PasswordToken.objects.get_or_create(user=user) if token.expired() or token.being_expired(): token.delete() token, created = PasswordToken.objects.get_or_create(user=user) return Response({'token': token.key})
class ReleaseMappingStats(APIView): """ Species latest release mapped/unmapped stats (Swissprot/Ensembl) """ schema = ManualSchema( description= "Species latest release mapped/unmapped stats (Swissprot/Ensembl)", fields=[ coreapi.Field(name="taxid", required=True, location="path", schema=coreschema.Integer(), description="Taxonomy id"), ]) def get(self, request, taxid): # client is interested in latest release mapping history try: # find the release stats for the species latest release mapping rmh = ReleaseMappingHistory.objects.filter( uniprot_taxid=taxid).latest('release_mapping_history_id') release_stats = ReleaseStats.objects.get( release_mapping_history=rmh) except: raise Http404(( "Unable to find stats for latest species {} release mapping history" ).format(taxid)) serializer = ReleaseStatsSerializer(release_stats) return Response(serializer.data)
class RequestRestoreCodeViewSet(viewsets.ViewSet): """Resource to handle the request of a restore password code.""" schema = ManualSchema( encoding="application/json", fields=[ coreapi.Field( "email", required=True, location="body", schema=coreschema.String( description=_( "Email of the user who is requesting a new code for restore his password." ) ), ) ], ) def create(self, request): serializer = RequestRestoreCodeSerializer(data=request.data) if serializer.is_valid(): email = serializer.validated_data["email"] user = User.objects.get(email=email) user.send_restore_code() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class MappingLabelsView(APIView): """ Retrieve all labels for a given mapping """ schema = ManualSchema( description="Retrieve all labels for a given mapping", 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) all_labels = CvUeLabel.objects.all() mapping_labels = mapping.labels.values_list('label', flat=True) label_map = [] for label in all_labels: label_map.append({ 'label': label.description, 'id': label.id, 'status': label.id in mapping_labels }) data = {'labels': label_map} serializer = LabelsSerializer(data) return Response(serializer.data)
class CountryGeomView(APIView): """ Get minimal geojson of requested country. This works for one country only due to response size but can probably be reduced with ST_dump / ST_union for multiple countries. """ schema = ManualSchema(fields=[ coreapi.Field( "country_id", required=False, location="query", description="Country ID", schema=coreschema.Integer(), ), ]) http_method_names = ['get'] def get(self, request, *args, **kwargs): return Response( data={ 'type': 'Feature', 'geometry': json.loads(self.get_queryset().simple_geom) }) def get_queryset(self): try: return Country.objects.extra( select={ 'simple_geom': 'ST_AsGeoJSON(ST_Simplify(geom, 0.01))' }).get(id=self.request.GET.get('country_id')) except Country.DoesNotExist: raise Http404
class MappingAlignmentDifference(APIView): """ Update a mapping's alignment difference """ permission_classes = (IsAuthenticated, ) schema = ManualSchema( description="Update a mapping's alignment difference", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the mapping"), coreapi.Field( name="difference", required=True, location="path", schema=coreschema.Integer(), description="An integer representing the alignment difference" ), ]) def post(self, request, pk, difference): mapping = get_mapping(pk) mapping.alignment_difference = difference mapping.save() serializer = EnsemblUniprotMappingSerializer( MappingsSerializer.build_mapping(mapping)) return Response(serializer.data)
class CustomAuthToken(ObtainAuthToken): """ CustomAuthToken is subclassing the ObtainAuthToken Ths class basically lets employees get their token by providing email and password, like a login form. """ serializer_class = AuthCustomTokenSerializer if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="email", required=True, location='form', schema=coreschema.String( title="Email", description="Valid email for authentication", ), ), coreapi.Field( name="password", required=True, location='form', schema=coreschema.String( title="Password", description="Valid password for authentication", ), ), ], encoding="application/json", )
class MappingPairwiseAlignment(APIView): """ Retrieve a set of pairwise alignments for a single mapping """ schema = ManualSchema( description= "Retrieve a set of pairwise alignments for a single mapping", 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): try: mapping = Mapping.objects.prefetch_related( 'alignments').select_related('transcript').select_related( 'uniprot').get(pk=pk) alignments = fetch_pairwise(mapping) except Exception as e: pprint.pprint(e) raise Http404 serializer = MappingAlignmentsSerializer(alignments) return Response(serializer.data)
class MyAuthToken(auth_views.ObtainAuthToken): serializer_class = MyAuthTokenSerializer if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="phone", required=True, location='form', schema=coreschema.String( title="Mobile Number", description="Valid mobile number for authentication", ), ), coreapi.Field( name="password", required=True, location='form', schema=coreschema.String( title="Password", description="Valid password for authentication", ), ), ], encoding="application/json", )
class ObtainCustomAuthToken(ObtainAuthToken): if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="username", required=True, location='form', schema=coreschema.String( title="Username", description="Valid username for authentication", ), ), coreapi.Field( name="password", required=True, location='form', schema=coreschema.String( title="Password", description="Valid password for authentication", ), ), ], description="""{RETRIEVE}""".format(RETRIEVE=_( "Service to log in using token, with username and password"), ), encoding="application/json", )
class GetLabels(APIView): """ Retrieve all labels for a given unmapped entry """ schema = ManualSchema(description="Retrieve all labels 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 given unmapped entry" ),]) def get(self, request, mapping_view_id): uniprot_entry = get_uniprot_entry(mapping_view_id) all_labels = CvUeLabel.objects.all() entry_labels = uniprot_entry.labels.values_list('label', flat=True) label_map = [] for label in all_labels: label_map.append({ 'label': label.description, 'id': label.id, 'status': True if label.id in entry_labels else False }) data = { 'labels': label_map } serializer = LabelsSerializer(data) return Response(serializer.data)
class CreateUserView(CreateAPIView): if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="username", required=True, location='form', schema=coreschema.String( title="username", description="username", ), ), coreapi.Field( name="password", required=True, location='form', schema=coreschema.String( title="password", description="password", ), ) ], encoding="application/json", ) model = User permission_classes = [ permissions.AllowAny # Or anon users can't register ] serializer_class = RegSerializer
class UnmappedDetailed(APIView): """ Retrieve a single "unmapped" entry, includes related entries. """ schema = ManualSchema(description="Retrieve a single unmapped entry, includes related entries.", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the mapping view id" ),]) def get(self, request, mapping_view_id): try: mapping_view = MappingView.objects.get(pk=mapping_view_id) except MappingView.DoesNotExist: raise Http404 # this is supposed to be called for an unmapped entry if mapping_view.uniprot_mapping_status == 'mapped' and mapping_view.mapping_id is not None: return Response({ "error":"Entry is mapped with id {}".format(mapping_view.mapping_id) }, status=status.HTTP_400_BAD_REQUEST) data = { 'entry': mapping_view, 'relatedEntries': list(MappingView.objects.filter(grouping_id=mapping_view.grouping_id).exclude(pk=mapping_view_id)) } serializer = UnmappedEntrySerializer(data) return Response(serializer.data)
class LocationView(generics.RetrieveAPIView): """ 地域の情報を取得するエンドポイント """ serializer_class = LocationSerializer permission_classes = (permissions.AllowAny,) schema = ManualSchema([ coreapi.Field( 'lat', required=True, location='query', schema=coreschema.String(description='latitude'), example='35.048900', description='緯度' ), coreapi.Field( 'lon', required=True, location='query', schema=coreschema.String(description='longitude'), example='135.780418', description='経度' ), ]) def retrieve(self, request, *args, **kwargs): lat = request.query_params.get('lat') lon = request.query_params.get('lon') if lat is None or lon is None: return Response(status=status.HTTP_400_BAD_REQUEST) instance = self.get_object() serializer = self.get_serializer(instance) return Response(serializer.data) def get_object(self): """クエリパラメータから緯度経度取得して情報を返す""" lat = self.request.query_params.get('lat') lon = self.request.query_params.get('lon') reporter = DisasterReport(lat, lon) loc = reporter.get_area_info() rain_reporter = RainReporter(lat, lon) rain_reporter.get_report(loc) return loc