class CustomSchema(ViewInspector, LogsSearchPaginableSchema): def __init__(self, **kwargs): super().__init__() manual_fields = kwargs.get('manual_fields', None) self.fields_post = [] self.fields_get = [] self.autoschema = AutoSchema(manual_fields) for k, v in kwargs.items(): setattr(self, k, v) def get_link(self, path, method, base_url): self.autoschema.view = self.view fields = self.get_path_fields(path, method) fields += self.get_pagination_fields(path, method) manual_fields = self.autoschema.get_manual_fields(path, method) fields = self.autoschema.update_fields(fields, manual_fields) link = self.autoschema.get_link(path, method, base_url) return coreapi.Link(url=link.url, action=method.lower(), encoding=link.encoding, fields=fields, description=link.description) # Implement custom introspection here (or in other sub-methods) def get_path_fields(self, path, method): lower_method = method.lower() fields = getattr(self, "fields_{}".format(lower_method), []) return fields
def __init__(self, **kwargs): super().__init__() manual_fields = kwargs.get('manual_fields', None) self.fields_post = [] self.fields_get = [] self.autoschema = AutoSchema(manual_fields) for k, v in kwargs.items(): setattr(self, k, v)
def __init__( self, view, path, method, components, request, overrides, operation_keys=None ): super(SwaggerAutoSchema, self).__init__( view, path, method, components, request, overrides ) self._sch = AutoSchema() self._sch.view = view self.operation_keys = operation_keys
class GeoView(object): """ Perform Geo calls """ @staticmethod def register(): urlpatterns = [ path('geo/getGeoData/', GeoView.getGeoData), path('geo/getGeoDetail/', GeoView.getGeoDetail), path('geo/getBubbleInfo/', GeoView.getBubbleInfo), ] return urlpatterns @staticmethod @api_view(['GET']) @permission_classes((permissions.IsAuthenticated, )) @schema( AutoSchema(manual_fields=[ coreapi.Field("quey", required=True, description="Geo query") ])) def getGeoData(request, *args, **kargs): serializer = GeoQuerySerializer(data=request.query_params) serializer.is_valid(raise_exception=True) service = GeoService(request) node_data = service.getGeoData(serializer.create(serializer.data)) serializer = GeoDataSerializer(node_data) return Response(serializer.data) @staticmethod @api_view(['GET']) @permission_classes((permissions.IsAuthenticated, )) @schema( AutoSchema(manual_fields=[ coreapi.Field("quey", required=True, description="Geo query") ])) def getGeoDetail(request, *args, **kargs): pass @staticmethod @api_view(['GET']) @permission_classes((permissions.IsAuthenticated, )) @schema( AutoSchema(manual_fields=[ coreapi.Field("quey", required=True, description="Geo query") ])) def getBubbleInfo(request, *args, **kargs): raise exceptions.NotFound("NOT YEY IMPLEMENTED")
class FetchWorkOrdersView(APIView): """ get: Fetch orders sorted by deadline can be specific to any worker or all """ schema = AutoSchema(manual_fields=[ coreapi.Field( "worker_id", location='query', description= 'Enter worker id for fetching orders related to worker else ignore it' ), ]) def get(self, request): worker_id = request.GET.get('worker_id') if worker_id: queryset = WorkerOrderAssignment.objects.filter( worker_id=worker_id) else: queryset = WorkerOrderAssignment.objects.all() queryset = queryset.order_by('order__deadline') serializer = WorkOrderInfoSerializer(queryset, many=True) return Response({'detail': serializer.data})
class ResetPasswordCheck(APIView): """ Una vista Api que proporciona un método para verificar que un token sea válido. """ throttle_classes = () permission_classes = () parser_classes = ( parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser, ) renderer_classes = (renderers.JSONRenderer, ) serializer_class = TokenSerializer schema = AutoSchema(manual_fields=[ coreapi.Field('token', location='body', required=True), ]) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) token = filter_parameters_from_token( serializer.validated_data['token']) # encontrar token reset_password_token = ResetPasswordToken.objects.filter( key=token).first() if reset_password_token is None: return Response({'error': 'token not found'}, status=status.HTTP_404_NOT_FOUND) if reset_password_token.expired: return Response({'error': 'token expired'}, status=status.HTTP_400_BAD_REQUEST) if reset_password_token.used: return Response({'error': 'token used'}, status=status.HTTP_400_BAD_REQUEST) password_reset_token_validation_time = get_password_reset_token_expiry_time( is_long_token=reset_password_token.is_long_token) # comprobar fecha de caducidad expiry_date = reset_password_token.created_at + timedelta( hours=password_reset_token_validation_time) if timezone.now() > expiry_date: # marca token como caducada reset_password_token.expired = True reset_password_token.used = True reset_password_token.save() return Response({'error': 'token expired'}, status=status.HTTP_400_BAD_REQUEST) if not reset_password_token.user.is_active: return Response({'error': 'inactive user'}, status=status.HTTP_400_BAD_REQUEST) return Response()
class SearchCriteria(APIView): """ Search criteria based on specified terms. """ permission_classes = (IsAuthenticated, ) schema = AutoSchema(manual_fields=[ coreapi.Field("query", required=True, location="query", schema=coreschema.String()), ]) def post(self, request): """ Return a list of all users. """ if "terms" not in request.data: return Response({"query": ["This field is required."]}, status=status.HTTP_400_BAD_REQUEST) # TODO # Execute query(terms) in SolR result = {} return Response(result)
def build_documentation_for_request_serializer(serializer_class, location): """ Generate an AutoSchema instance for use in documenting a django-rest-framework API view. The return value of this function should be set as the view `schema` class attribute. :param serializer_class: (serializers.Serializer) django-rest-framework serializer for validating request data :param location: (str) Method used for the requests to this view. Should be one of [path, query, form, body] :return: (rest_framework.schemas.AutoSchema) """ serializer = serializer_class() serializer_fields = [f for f in serializer.fields.items()] fields = [] field_class_to_type_map = { base.fields.CleanedChoiceField: 'string', rest_framework.fields.CharField: 'string', rest_framework.fields.FloatField: 'float', rest_framework.fields.IntegerField: 'integer', rest_framework.serializers.BooleanField: 'boolean', } for name, field in serializer_fields: fields.append( coreapi.Field(name, required=field.required, location=location, type=field_class_to_type_map.get( type(field), 'string'), description=field.help_text)) return AutoSchema(manual_fields=fields)
class StateList(APIView, PageNumberPagination): """ List all states Get a particular state """ # Schema for Swagger docs schema = AutoSchema(manual_fields=[ coreapi.Field( "name", required=False, location='query', description='Get a particular Nigerian state by its name') ]) def get(self, request): # try to get the query parameter if request.GET.get('name', False): param = request.GET['name'].capitalize() obj = State() data = obj.getState(param) else: obj = State() data = obj.getAll() if data: return Response(data) else: return Response(data={'details': 'No content was found'}, status=status.HTTP_204_NO_CONTENT)
class UrlServicesCreateView(APIView): """ This View is responsible to storage and create an URL object """ media_type = 'application/json' _service_class = UrlShortenerService serializer_class = UrlShortenerSerializer schema = AutoSchema(manual_fields=[ coreapi.Field( 'url', required=True, location='body', description= 'This method expecting a Json object like this: {"url": "www.website.com"}', schema=coreschema.String()), ]) def post(self, request): body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) _url = body_data['url'] _service = self._service_class() result = _service.shorten_url(_url) return result
class CustomView(APIView): schema = AutoSchema(manual_fields=[ coreapi.Field("my_extra_field", required=True, location="path", schema=coreschema.String()), ])
class BusinessesListAPI(APIView): def get(self, request): category = request.GET.get('category') if category: businesses = Business.objects.filter(category=category) else: businesses = Business.objects.all() result = [{ 'name': business_details.name, 'address': business_details.address, 'phone_number': business_details.phone_number, 'category': business_details.category, 'logo': business_details.logo.path, 'reviews': business_details.get_reviews() } for business_details in businesses] return Response({ 'success': True, 'results': result }, status=status.HTTP_200_OK) schema = AutoSchema(manual_fields=[ coreapi.Field("category", False, description="one of the categories in the list: %s" % get_categories()), ])
class SDKIdentitiesDeprecated(SDKAPIView): """ THIS ENDPOINT IS DEPRECATED. Please use `/identities/?identifier=<identifier>` instead. """ # API to handle /api/v1/identities/ endpoint to return Flags and Traits for user Identity # if Identity does not exist it will create one, otherwise will fetch existing serializer_class = IdentifyWithTraitsSerializer schema = AutoSchema(manual_fields=[ coreapi.Field( "X-Environment-Key", location="header", description="API Key for an Environment", ), coreapi.Field( "identifier", location="path", required=True, description="Identity user identifier", ), ]) # identifier is in a path parameter def get(self, request, identifier, *args, **kwargs): # if we have identifier fetch, or create if does not exist if identifier: identity, _ = Identity.objects.get_or_create( identifier=identifier, environment=request.environment, ) else: return Response({"detail": "Missing identifier"}, status=status.HTTP_400_BAD_REQUEST) if identity: traits_data = identity.get_all_user_traits() # traits_data = self.get_serializer(identity.get_all_user_traits(), many=True) # return Response(traits.data, status=status.HTTP_200_OK) else: return Response( {"detail": "Given identifier not found"}, status=status.HTTP_404_NOT_FOUND, ) # We need object type to pass into our IdentitySerializerTraitFlags IdentityFlagsWithTraitsAndSegments = namedtuple( "IdentityTraitFlagsSegments", ("flags", "traits", "segments")) identity_flags_traits_segments = IdentityFlagsWithTraitsAndSegments( flags=identity.get_all_feature_states(), traits=traits_data, segments=identity.get_segments(), ) serializer = IdentitySerializerWithTraitsAndSegments( identity_flags_traits_segments) return Response(serializer.data, status=status.HTTP_200_OK)
class ReviewBusinessAPI(APIView): def post(self, request): business_id = request.data.get('business_id') stars = request.data.get('stars') comment = request.data.get('comment') reviewer = request.data.get('reviewer_name') try: business = Business.objects.get(id=business_id) except Exception as e: return Response( { 'Error': 'Could not retrieve Business with id ' + business_id + ' ' + str(e) }, status=status.HTTP_400_BAD_REQUEST) Review.objects.create(stars=stars, comment=comment, business=business, reviewer=reviewer) return Response( { 'success': True, 'message': 'Review successfully created' }, status=status.HTTP_201_CREATED) schema = AutoSchema(manual_fields=[ coreapi.Field("business_id", True, description="1-indexed DB id"), coreapi.Field("stars", True, description="a number from 1 to 5"), coreapi.Field("comment", False, description="ex: 'Amazing place'"), coreapi.Field( "reviewer_name", False, description="Name of the reviewer"), ])
class CustomPasswordChangeView(GenericAPIView): serializer_class = PasswordChangeSerializer permission_classes = (IsAuthenticated, ) schema = AutoSchema(manual_fields=[ coreapi.Field("curr_password", description="Current Password", location="form", required=True, schema=coreschema.String()) ]) def post(self, request, *args, **kwargs): data = { 'new_password1': request.data.get('new_password1'), 'new_password2': request.data.get('new_password2') } if (check_password(request.data.get('curr_password'), self.request.user.password)): serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response({"detail": _("New password has been saved.")}) else: return Response({"detail": _("New password has not been saved.")})
class LoginView(APIView): permission_classes = (AllowAny, ) schema = AutoSchema(manual_fields=[ coreapi.Field("username", description="User email"), coreapi.Field("password", description="User password"), ]) @classmethod def post(cls, request: Request, *args, **kwargs): """ Authenticate an user. """ username = get_param_or_400(request.data, "username", str) password = get_param_or_400(request.data, "password", str) print(f"Password for login method: {password}") ## Decrypt the password password = decrypt_pass(password) user = authenticate(username=username, password=password) if user: login(request, user) data = UserSerializer(user).data return Response(data=data) else: raise exceptions.AuthenticationFailed( _("Invalid username/password."))
class SubGroupIndicatorView(APIView): """ Return a list of a subgroups indicators """ schema = AutoSchema(manual_fields=[ coreapi.Field('gid', required=True, location='path', schema=coreschema.String( description='Unique group identifier')), ]) serializer_class = serializers.GroupingSerializer def get(self, request, gid, format=None): indi_exists = Indicator\ .objects\ .filter(parentgid=gid)\ .exists() if indi_exists: query = Grouping.objects\ .filter(gid=gid)\ .select_related('parentgid') else: query = Grouping.objects\ .filter(parentgid=gid)\ .select_related('parentgid') serialize = serializers.GroupingSerializer( query, context={'request': request}, many=True) return Response({'results': serialize.data})
class ParkingHistory(auth.AuthenticateddAPIView): ''' Return historic car park occupancy data for a single car park identified by _parking_id_. Data is returned in 24-hour chunks from _start_date_ to _end_date_ inclusive. A most 31 day's data can be retrieved in a single request. ''' schema = AutoSchema(manual_fields=parking_id_fields + list_args_fields) def get(self, request, parking_id): args = util.ListArgsSerializer(data=request.query_params) args.is_valid(raise_exception=True) # Note that this validates parking_id! config = get_parking_config(parking_id) feed_id = config['feed_id'] start_date = args.validated_data.get('start_date') end_date = args.validated_data.get('end_date') if end_date is None: end_date = start_date day_count = (end_date - start_date).days + 1 results = [] for date in (start_date + timedelta(n) for n in range(day_count)): try: filename = ( '{0}/data_park/{2:%Y}/{2:%m}/{2:%d}/{1}_{2:%Y-%m-%d}.txt'. format(feed_id, parking_id, date)) results = results + util.read_json_fragments(filename) except FileNotFoundError: pass serializer = ParkingHistorySerializer({'request_data': results}) return Response(serializer.data)
def test_update_fields(self): """ That updating fields by-name helper is correct Recall: `update_fields(fields, update_with)` """ schema = AutoSchema() fields = [] # Adds a field... fields = schema.update_fields(fields, [ coreapi.Field("my_field", required=True, location="path", schema=coreschema.String()), ]) assert len(fields) == 1 assert fields[0].name == "my_field" # Replaces a field... fields = schema.update_fields(fields, [ coreapi.Field("my_field", required=False, location="path", schema=coreschema.String()), ]) assert len(fields) == 1 assert fields[0].required is False
class LoginView(CustomView): required_params = ['user', 'password'] permission_classes = () schema = AutoSchema(manual_fields=[ coreapi.Field( "user", required=True, location="form", schema=coreschema.String()), coreapi.Field("password", required=True, location="form", schema=coreschema.String()), ]) def post(self, request, format=None): try: user = request.data["user"] password = request.data["password"] user = authenticate(username=user, password=password) if user is not None: if user.is_active: login(request, user) token = Token.objects.get_or_create(user=user)[0] return Response({"success": True, "Token": token.key}) except Exception as e: return Response({'msg': str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response({}) '''
class DeleteKeyView(APIView): """ 删除key """ schema = AutoSchema(manual_fields=[ coreapi.Field(name='hostname', required=True, location='form', description='主机列表', type='array'), ]) def check_object(self, hostname): try: obj = MinionsStatus.objects.get(minion_id=hostname) return obj.minion_id except MinionsStatus.DoesNotExist: contenxt = hostname + " doesn't exist" raise APIException(contenxt) def delete(self, request): hostnames = request.data.get('hostname', None) for hostname in hostnames: minion_id = self.check_object(hostname) salt_api = SaltAPI() salt_api.delete_key(minion_id) return Response({"status": 1})
class SubmitContestSolution(SubmitSolution): permission_classes = ( IsAuthenticated, CanEnterContest, ) schema = AutoSchema([ make_path_coreapi_schema( name='contest_name', title='Contest name', description='Name of the contest to which you want to submit ' 'solution. You can find it after /c/ in urls ' 'when using SIO 2 web interface.', ), make_path_coreapi_schema( name='problem_short_name', title='Problem short name', description='Short name of the problem to which you want to submit ' 'solution. You can find it for example in first column ' 'of problem list when using SIO 2 web interface.', ), ]) def get_problem_instance(self, contest_name, problem_short_name): return get_object_or_404(ProblemInstance, contest=contest_name, short_name=problem_short_name)
class CurrentTalent(APIView): # authentication_classes = (authentication.TokenAuthentication, ) # permission_classes = (permissions.IsAuthenticated,) schema = AutoSchema(manual_fields=[ coreapi.Field( "Authorization", required=True, location="header", description="Use bearer token from login: ex: Bearer \{token\}", schema=coreschema.String()), ]) def get_object(self, user): try: user = User.objects.get(pk=user.pk) talent = Talent.objects.get(user=user.id) return talent except Talent.DoesNotExist: raise Http404 """ Get current talent info """ def get(self, request, format=None): talent_item = self.get_object(request.user) serializer = TalentSerializer(talent_item) return Response(serializer.data)
class CompanyAddressView(APIView): """ get: Returns all address of given company post: Add a new address to the given company """ schema = AutoSchema([ coreapi.Field("company_id", required=True, location='path', description='Enter Company id') ]) def get_serializer(self, *args, **kwargs): return CompanyAddressSerialzier() def get(self, request, company_id): queryset = CompanyAddress.objects.filter(company_id=company_id) serializer = CompanyAddressSerialzier(queryset, many=True) return Response(serializer.data) def post(self, request, company_id): serializer = CompanyAddressSerialzier(data=request.data) if serializer.is_valid(): serializer.save(company_id=company_id) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class CityList(APIView): """ List all states Get a particular city or state """ schema = AutoSchema(manual_fields=[ coreapi.Field( "name", required=False, location='query', description='Get a particular Nigerian city or town by its name') ]) def get(self, request): if request.GET.get('name', False): param = request.GET['name'].capitalize() obj = City() data = obj.getCity(param) else: obj = City() data = obj.getAll() if data: return Response(data) else: return Response({'details': 'No content was found'}, status=status.HTTP_204_NO_CONTENT)
class CheckAlphabet(APIView): ''' simple APIView for alphacheck api ''' schema = AutoSchema(manual_fields=[ coreapi.Field( 'case_insensitive', required=False, location='query', schema=coreschema.Boolean(), ), ]) # pylint: disable=redefined-builtin, unused-argument def get(self, request, query, format=None): ''' HTTP GET method that checks whether query contains all letters of the alphabet ''' try: case_insensitive = json.loads( request.query_params.get('case_insensitive', 'false')) except json.JSONDecodeError: case_insensitive = False try: response = has_all_alphabet(query, case_insensitive=case_insensitive, version=request.version) except KeyError: raise Http404 return Response({ 'response': response, })
class UserAccount(APIView): authentication_classes = [OAuth2Authentication] permission_classes = [AllowAny] serializer_class = UserSerializer schema = AutoSchema(manual_fields=[ coreapi.Field('username', location='form'), coreapi.Field('password', location='form'), # coreapi.Field('client_id', location='form'), # coreapi.Field('client_secret', location='form'), coreapi.Field('refresh_token', location='form'), ]) # update user password def put(self, request): _dict = {_key: _val[0] for _key, _val in dict(request.data).items()} _dict['username'] = request.user.username serializer = UserSerializer(User.objects.get(pk=request.user.id), data=_dict) if serializer.is_valid(): serializer.save() return Response("succeed") def delete(self, request): # logout try: request.user.auth_token.delete() except (AttributeError, ObjectDoesNotExist): pass return Response('logout')
class BarDataView(APIView): schema = AutoSchema([ coreapi.Field("contract", True, "form", type="string", description="Contract Id"), coreapi.Field("freq", True, "form", type="string", description="Bar Frequency"), coreapi.Field("start_dt", False, "form", type="string", description="start datetime"), coreapi.Field("end_dt", False, "form", type="string", description="end datetime"), ]) def get(self, request): """从arctic数据库中拉取K线数据""" contract = request.query_params['contract'] freq = request.query_params['freq'] start_dt = request.query_params.get('start_dt') end_dt = request.query_params.get('end_dt') lib = ac.get_library(f"bar.{freq}") date_range = DateRange(start_dt, end_dt) data = lib.read(contract, date_range=date_range) return data.to_dict(orient='index')
class ProjectViewSet(viewsets.ModelViewSet): Schema = AutoSchema(manual_fields=[ coreapi.Field(name="projectName", required=False, location="query", schema=coreschema.String(description='项目名'), ) ]) schema = Schema authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) serializer_class = ProjectSerializer pagination_class = pagination.LimitOffsetPagination def get_queryset(self): project_name = self.request.GET.get('projectName') if project_name: return ProjectModel.objects.filter(name__icontains=project_name).order_by("-id") else: return ProjectModel.objects.all().order_by("-id") def list(self, request, *args, **kwargs): projects = self.get_queryset() page = self.paginate_queryset(projects) serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) def destroy(self, request, *args, **kwargs): instance = ProjectModel.objects.get(id=kwargs.get('pk')) self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT)
class BenchmarkMandateView(APIView): """ Return mandate rankings for for a particular government category """ schema = AutoSchema(manual_fields=[ coreapi.Field('category', required=True, location='query', schema=coreschema.String( description='Unique government category ID')), coreapi.Field('year', required=False, location='query', schema=coreschema.String( description='full year eg: 2016')), ]) def get(self, request, format=None): year = self.request\ .query_params.get('year', Yearref.objects.latest('yearid').yr) category = self.request.query_params.get('category', None) if category is None: return Response(status=status.HTTP_400_BAD_REQUEST) query = Govrank\ .objects\ .filter(govid__gcid=category, yearid__yr=year) serialize = serializers.BenchmarkMandateSerializer( query, context={'request': request}, many=True, ) return Response({'results': serialize.data})