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) email_recipients_list = { recipient_id: recipient_details.get('name') for (recipient_id, recipient_details) in settings.EMAIL_RECIPIENT_LIST.items() } data = { 'entry': mapping_view, 'relatedEntries': list( MappingView.objects.filter( grouping_id=mapping_view.grouping_id).exclude( pk=mapping_view_id)), 'emailRecipientsList': email_recipients_list } serializer = UnmappedEntrySerializer(data) serializer.data['entry']['status'] = MappingView.status_description( serializer.data['entry']['status']) return Response(serializer.data)
class RoomView(APIView): CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' schema = AutoSchema(manual_fields=[ coreapi.Field(name='room_id', required=True, location='path', schema=coreschema.Integer( description='Identifier of the room')), ]) @staticmethod def _map_number_to_char(number): if number - 1 >= len(RoomView.CHARS): return None else: return RoomView.CHARS[number - 1] @staticmethod def _transform_row(row): previous_seat = [0, 0] result = [] for seat, column in zip(row, range(1, len(row) + 1)): result += [None for _ in range(seat[1] - previous_seat[1] - 1)] result.append({'col': column, 'seat': seat}) previous_seat = seat return result @staticmethod def _transform_layout(rows, raw_layout): layout = [] empty = 0 for current_row in range(1, rows + 1): row = [i for i in raw_layout if i[0] == current_row] if len(row): layout.append({ 'row': RoomView._map_number_to_char(current_row - empty), 'seats': RoomView._transform_row(row) }) else: layout.append(None) empty += 1 return layout def get(self, request, room_id, format=None): """ Returns details of the room for given showing """ try: room = Room.objects.get(pk=room_id) serializer = RoomSerializer(room) layout = self._transform_layout(serializer.data['rows'], serializer.data['layout']) data = serializer.data data['layout'] = layout return Response(data) except ObjectDoesNotExist: raise Http404
def setUp(self): self.field = coreapi.Field( name='page', required=True, location='query', schema=coreschema.Integer(description='A page number.')) self.swagger = _get_parameters(coreapi.Link(fields=[self.field]), encoding='')
class ShowingListView(APIView): schema = AutoSchema(manual_fields=[ coreapi.Field(name='date', required=True, location='path', schema=coreschema.String( description='Date in format YYYY-MM-DD')), coreapi.Field(name='cinema_id', required=True, location='path', schema=coreschema.Integer( description='Identifier of the cinema')), coreapi.Field(name='movie_id', required=True, location='path', schema=coreschema.Integer( description='Identifier of the movie')), ]) def get(self, request, movie_id, date, cinema_id, format=None): """ Returns list of all showings for given movie id and given day """ datetime_date = datetime.strptime(date, '%Y-%m-%d').date() if datetime_date < datetime.now().date(): return Response([]) elif datetime_date == datetime.now().date(): showing = Showing.objects \ .prefetch_related() \ .filter(room__cinema__id=cinema_id, movie__id=movie_id, date=date, hour__gt=datetime.now() + timedelta(minutes=15)) \ .all() \ .order_by('hour') else: showing = Showing.objects \ .prefetch_related() \ .filter(room__cinema__id=cinema_id, movie__id=movie_id, date=date) \ .all() \ .order_by('hour') serializer = ShowingSerializer(showing, many=True) return Response(serializer.data)
def get_schema_fields(self, view): fields = [ coreapi.Field( name="place", description="show meals in specified place", required=False, location='query', schema=coreschema.Integer() ), coreapi.Field( name="ingredients", description="show meals with specified ingredients", required=False, location='query', schema=coreschema.Integer() )] return fields
def get_schema_fields(self, view): fields = [ coreapi.Field( name="meal", description="show ingredients in specified meal", required=False, location='query', schema=coreschema.Integer() ), coreapi.Field( name="calories", description="show ingredients with specified number of calories", required=False, location='query', schema=coreschema.Integer() )] return fields
def get_link(self, path, method, base_url): link = super().get_link(path, method, base_url) if method == 'POST': fields = [ coreapi.Field( "file[]", required=False, location="form", schema=coreschema.String(title='file[]', description='A multipart list of files to upload.') ), coreapi.Field( "course", required=False, location="form", schema=coreschema.Integer(title='course', description=Attachment._meta.get_field('course').help_text) ), coreapi.Field( "event", required=False, location="form", schema=coreschema.Integer(title='event', description=Attachment._meta.get_field('event').help_text) ), coreapi.Field( "homework", required=False, location="form", schema=coreschema.Integer(title='homework', description=Attachment._meta.get_field('homework').help_text) ) ] return coreapi.Link( url=link.url, action=link.action, encoding=link.encoding, fields=fields, description=link.description ) return link
def get_schema_fields(self, view): return (Field( name='near_trek', required=False, location='query', schema=coreschema.Integer( title=_("Near trek"), description= _("Id of a trek. It will show only the touristics contents related to this trek" ))), )
def get_schema_fields(self, view): return ( Field(name='type', required=False, location='query', schema=coreschema.Integer( title=_("Type"), description=_( "Limit to POIs that contains a specific POI Type"))), Field( name='trek', required=False, location='query', schema=coreschema.Integer( title=_("Trek"), description= _("Id of a trek. It will show only the POIs related to this trek" ))), )
def get_schema_fields(self, view): return [ coreapi.Field( name='month', required=False, schema=coreschema.Integer( description='The reference month number [1-12]'), location='query', type=int, ), coreapi.Field( name='year', required=False, schema=coreschema.Integer( description='The reference year number (eg 2018)'), location='query', type=int, ), ]
def _annotated_type_to_coreschema( annotated_type: type) -> coreschema.schemas.Schema: if annotated_type is bool or issubclass(annotated_type, schema.Boolean): return coreschema.Boolean() elif annotated_type is int or issubclass(annotated_type, schema.Integer): return coreschema.Integer() elif annotated_type is float or issubclass(annotated_type, schema.Number): return coreschema.Number() return coreschema.String()
def get_serializer_fields(self, path, method): fields = [] if method == 'POST': fields = [ coreapi.Field( name="user_id", required=True, location="form", schema=coreschema.Integer(title="user_id", description="Id пользователя"), description='user_id' ), coreapi.Field( name="group_id", required=True, location="form", schema=coreschema.Integer(title="group_id", description="Id группы"), description='group_id' ), coreapi.Field( name="role", required=True, location="form", schema=coreschema.String(title="role", description="Роль"), description='Значение ADM или USR', ), ] if method == 'PUT': fields = [ coreapi.Field( name="role", required=True, location="form", schema=coreschema.String(title="role", description="Роль"), description='Значение ADM или USR', ), ] return fields
def get_manual_fields(self, path, method): if method == 'PUT': return [ coreapi.Field('default_client_id', required=True, location='form', schema=coreschema.Integer( description='Default client ID')), ] elif method == 'GET': return []
def get_serializer_fields(self, path, method): fields = [] if method == 'POST': fields = [ coreapi.Field(name="group_id", required=True, location="form", schema=coreschema.Integer( title="group", description="Id группы"), description='group_id'), coreapi.Field( name="title", required=True, location="form", schema=coreschema.String(title="title", description="Название задачи"), description='Название задачи', ), coreapi.Field( name="user", required=True, location="form", schema=coreschema.Array(title="user", description="Юзеры в задаче"), description='Юзеры в задаче', ), ] if method == 'PUT': fields = [ coreapi.Field(name="done", required=True, location="form", schema=coreschema.Boolean( title="done", description="Завершено"), description='Завершено'), coreapi.Field( name="title", required=True, location="form", schema=coreschema.String(title="title", description="Название задачи"), description='Название задачи', ), coreapi.Field( name="user", required=True, location="form", schema=coreschema.Array(title="user", description="Юзеры в задаче"), description='Юзеры в задаче', ), ] return fields
def get_manual_fields(self, path, method): if method == 'GET': return [ coreapi.Field( 'client_id', required=True, location='path', schema=coreschema.Integer(description='Client ID')), ] else: return []
def get_param_schema(annotated_type: typing.Type) -> coreschema.schemas.Schema: if issubclass(annotated_type, (bool, typesystem.Boolean)): return coreschema.Boolean() elif issubclass(annotated_type, int): return coreschema.Integer() elif issubclass(annotated_type, float): return coreschema.Number() elif issubclass(annotated_type, typesystem.Enum): enum = typing.cast(typing.Type[typesystem.Enum], annotated_type) return coreschema.Enum(enum=enum.enum) return coreschema.String()
def test_ref_space(): schema = coreschema.RefSpace(refs={ 'PositiveInteger': coreschema.Integer(minimum=1), 'Root': coreschema.Ref('PositiveInteger') | coreschema.String() }, root='Root') assert schema.validate(1) == [] assert schema.validate('abc') == [] assert schema.validate(0) == [('Must match one of the options.', [])]
class TriggerCasePlan(APIView): """ 【触发case测试计划】 """ Schema = AutoSchema(manual_fields=[ coreapi.Field(name="projectId", required=True, location="form", schema=coreschema.Integer(description='项目id')), coreapi.Field(name="testPlanId", required=True, location="form", schema=coreschema.String(description='接口测试计划uid')), ]) schema = Schema authentication_classes = (JSONWebTokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) def post(self, request): receive_data = request.data testplan_id = receive_data.get('testPlanId', None) project_id = receive_data.get('projectId', None) if not all([testplan_id, project_id]): return Response({"error": "缺少必要的参数"}, status=status.HTTP_400_BAD_REQUEST) case_test_plan = CaseTestPlanModel.objects.filter( project_id=project_id, plan_id=testplan_id).first() if not case_test_plan: return Response( {"error": "testplan {} not found".format(testplan_id)}, status=status.HTTP_404_NOT_FOUND) case_paths = case_test_plan.case_paths case_test_plan_task = CaseTestPlanTaskModel.objects.create( test_plan_uid=testplan_id, state=CaseTestPlanTaskState.WAITING, case_job_number=len(case_paths), finish_num=0) CaseRunner.distributor(case_test_plan_task) # 根据是否并行执行case选择不用的触发器 if case_test_plan.parallel: '''并行执行''' case_jobs_id = CaseJobModel.objects.filter( case_task_id=case_test_plan_task.id).values_list('id', flat=True) for case_job_id in case_jobs_id: case_test_job_executor.delay(case_job_id, project_id, case_test_plan.plan_id, case_test_plan_task.id) else: '''串行执行''' case_test_task_executor.delay(case_test_plan_task.id) return Response({"success": True, "data": "测试用例计划已经成功触发"})
def get_serializer_fields(self, path, method): extra_fields = [] if method == 'PUT': extra_fields = [ coreapi.Field(name='password', required=False, location='form', schema=coreschema.String( description="New password", title='password', )), coreapi.Field( name='position', required=False, location='form', type=coreschema.Integer, schema=coreschema.Integer( description= "Device outlet position. Mandatory for changing outlet name, remove user or outlet status. Must be an integer. Only admins can remove user from outlet", title="position")), coreapi.Field( name='name', required=False, location='form', schema=coreschema.String( description= "Change the outlet name in the position provided", title='name')), coreapi.Field( name='status', required=False, location='form', type=coreschema.String, schema=coreschema.String( description= "Turn on or off the remote server connected to the outlet position provided. Values accepted: \'on\' or \'off\'", title='status')), coreapi.Field( name='rempos', required=False, location='form', schema=coreschema.Boolean( description= "Remove user from position. Only for admins. Values accepted: True or False (False by default)", title='rempos', )), ] manual_fields = super(CustomUserRestSchema, self).get_serializer_fields(path, method) return manual_fields + extra_fields
class SpeciesHistoryAlignmentStatus(APIView): """ Update a species history's alignment status """ permission_classes = (IsAuthenticated,) schema = ManualSchema( description="Update a species history's alignment status", fields=[ coreapi.Field( name="id", required=True, location="path", schema=coreschema.Integer(), description="A unique integer value identifying the species history" ), coreapi.Field( name="status", required=True, location="path", schema=coreschema.Integer(), description="String representing the updated alignment status" ), ]) def post(self, request, pk, status): try: history = EnsemblSpeciesHistory.objects.get(pk=pk) except EnsemblSpeciesHistory.DoesNotExist: return Response( {"error": "Could not find species history {}".format(pk)}, status=status.HTTP_400_BAD_REQUEST ) else: history.alignment_status = status history.save() serializer = SpeciesHistorySerializer(history) return Response(serializer.data)
def get_serializer_fields(self, path, method): fields = [] if method == 'POST': fields = [ coreapi.Field(name='target', required=False, location="form", schema=coreschema.Integer(title='target', default=None, description='target'), description='target'), ] return fields
class ApiJobViewSet(viewsets.ModelViewSet): Schema = AutoSchema(manual_fields=[ coreapi.Field(name="task_id", required=False, location="query", schema=coreschema.Integer(description='api task id'), ), ]) schema = Schema authentication_classes = (JSONWebTokenAuthentication,) pagination_class = pagination.LimitOffsetPagination serializer_class = InterfaceJobSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): return InterfaceJobModel.objects.filter(api_test_plan_task_id=self.request.GET.get('task_id'))
def test_ref(): child = coreschema.Object(properties={ 'a': coreschema.String(), 'b': coreschema.Integer() }) schema = coreschema.Ref('Child') context = {'refs': {'Child': child}} assert schema.validate({'a': 'abc', 'b': 123}, context) == [] assert schema.validate({ 'a': 'abc', 'b': 'abc' }, context) == [('Must be an integer.', ['b'])]
def _annotated_type_to_coreschema( annotated_type: type) -> coreschema.schemas.Schema: if annotated_type is bool or issubclass(annotated_type, schema.Boolean): return coreschema.Boolean() elif annotated_type is int or issubclass(annotated_type, schema.Integer): return coreschema.Integer() elif annotated_type is float or issubclass(annotated_type, schema.Number): return coreschema.Number() elif issubclass(annotated_type, schema.Enum): enum = cast(Type[schema.Enum], annotated_type) return coreschema.Enum(enum=enum.enum) return coreschema.String()
def get_param_schema(annotated_type: typing.Type) -> coreschema.schemas.Schema: schema_kwargs = {'description': getattr(annotated_type, 'description', '')} if issubclass(annotated_type, (bool, typesystem.Boolean)): return coreschema.Boolean(**schema_kwargs) elif issubclass(annotated_type, int): return coreschema.Integer(**schema_kwargs) elif issubclass(annotated_type, float): return coreschema.Number(**schema_kwargs) elif issubclass(annotated_type, typesystem.Enum): enum = typing.cast(typing.Type[typesystem.Enum], annotated_type) return coreschema.Enum(enum=enum.enum, **schema_kwargs) return coreschema.String(**schema_kwargs)
class InvestorNetworkView(APIView): """ Get investor network. Used within charts section. """ schema = ManualSchema(fields=[ coreapi.Field( "operational_stakeholder", required=True, location="query", description="Operating company ID", schema=coreschema.Integer(), ), ]) def get_object(self): ''' Returns an investor object. ''' try: investor_id = int( self.request.query_params['operational_stakeholder']) except KeyError: raise serializers.ValidationError( {'operational_stakeholder': _("This field is required.")}) except ValueError: raise serializers.ValidationError( {'operational_stakeholder': _("An integer is required.")}) investor = get_object_or_404(HistoricalInvestor, pk=investor_id) if not self.request.user.is_authenticated: if investor.fk_status_id not in (InvestorBase.STATUS_ACTIVE, InvestorBase.STATUS_OVERWRITTEN): raise Http404("Investor is not public") self.check_object_permissions(self.request, investor) return investor def get(self, request, format=None): # TODO: determine what operational_stakeholder_diagram does here - # it seems to just be passed back in the response. operational_stakeholder = self.get_object() serialized_response = HistoricalInvestorNetworkSerializer( operational_stakeholder, user=request.user) #parent_type=request.query_params.get('parent_type', 'parent_stakeholders')) response_data = serialized_response.data.copy() #response_data['index'] = investor_diagram return Response(response_data)
class InterfaceViewSet(viewsets.ModelViewSet): Schema = AutoSchema(manual_fields=[ coreapi.Field( name="projectId", required=False, location="query", schema=coreschema.Integer(description='项目id'), ) ]) schema = Schema authentication_classes = (JSONWebTokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) serializer_class = InterfaceSerializer pagination_class = pagination.LimitOffsetPagination def get_queryset(self): if self.request.GET.get('projectId'): return InterfaceModel.objects.filter( project=self.request.GET.get('projectId')).order_by("-id") else: return InterfaceModel.objects.all().order_by("-id") def list(self, request, *args, **kwargs): """ 【获取接口列表】 """ interfaces = self.get_queryset() if not all([request.GET.get('limit'), request.GET.get('offset')]): serializer = self.get_serializer(interfaces, many=True) return Response({ "count": len(interfaces), "results": serializer.data }) page = self.paginate_queryset(interfaces) serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) def create(self, request, *args, **kwargs): """ 【创建接口】 """ serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) def destroy(self, request, *args, **kwargs): instance = InterfaceModel.objects.get(id=kwargs.get('pk')) self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT)
def get_serializer_fields(self, path, method): fields = [] if method == 'POST': fields = [ coreapi.Field(name='contact_user_id', required=True, location="form", schema=coreschema.Integer( title='contact_user_id', description='contact_user_id'), description='ID контакта'), ] return fields
class MappingDetailed(APIView): """ Retrieve a single mapping, includes related mappings/unmapped entries and taxonomy information. """ schema = ManualSchema( description=( "Retrieve a single mapping, includes related mappings/unmapped " "entries and taxonomy information."), 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) authenticated = False if request.user and request.user.is_authenticated: authenticated = True email_recipients_list = { recipient_id: recipient_details.get('name') for (recipient_id, recipient_details) in settings.EMAIL_RECIPIENT_LIST.items() } data = { 'taxonomy': build_taxonomy_data(mapping), 'mapping': MappingsSerializer.build_mapping(mapping, fetch_sequence=True, authenticated=authenticated), 'relatedEntries': { 'mapped': build_related_mappings_data(mapping), 'unmapped': build_related_unmapped_entries_data(mapping) }, 'emailRecipientsList': email_recipients_list } serializer = MappingSerializer(data) return Response(serializer.data)
def __init__(self, manual_fields=None): if manual_fields is None: manual_fields = [] manual_fields += [ coreapi.Field("course_group", required=True, location="path", schema=coreschema.Integer( title='id', description=Course._meta.get_field( 'course_group').help_text)), ] super().__init__(manual_fields=manual_fields)