Exemple #1
0
class ObtainSocialhomeAuthToken(ObtainAuthToken, APIView):
    # Documenting the API
    schema = AutoSchema(manual_fields=[
        coreapi.Field("username",
                      description="User's username",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("password",
                      description="User's password",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
    ])

    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)
        data = LimitedProfileSerializer(user.profile,
                                        context={
                                            "request": self.request
                                        }).data
        data.update({"token": token.key})
        return Response(data)
Exemple #2
0
 def get_schema_fields(self, view):
     return (
         Field(
             name='language',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("Language"),
                 description=
                 _("Set language for translation. Default: all. Example: fr"
                   ))),
         Field(
             name='fields',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("Fields"),
                 description=
                 _("Limit required fields to increase performances. Example: id,url,geometry"
                   ))),
         Field(
             name='omit',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("Omit"),
                 description=
                 _("Omit specified fields to increase performance. Example: url,category"
                   ))),
     )
Exemple #3
0
class ApiTask(APIView):
    """
    【case task接口】
    """
    Schema = AutoSchema(manual_fields=[
        coreapi.Field(name="ApiTestPlanUid", required=True, location="query",
                      schema=coreschema.String(description='接口测试计划uid')),
        coreapi.Field(name="limit", required=True, location="query",
                      schema=coreschema.String(description='limit')),
        coreapi.Field(name="offset", required=True, location="query",
                      schema=coreschema.String(description='offset')),
    ])
    schema = Schema
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        receive_data = request.GET
        interface_test_plan_uid = receive_data.get('ApiTestPlanUid', None)
        if not interface_test_plan_uid:
            return Response({"error": "缺少必要参数caseTestPlanUid"}, status=status.HTTP_400_BAD_REQUEST)
        pg = LimitOffsetPagination()
        api_tasks = ApiTestPlanTaskModel.objects.filter(test_plan_uid=interface_test_plan_uid).order_by('-id')
        page_api_tasks = pg.paginate_queryset(queryset=api_tasks, request=request, view=self)
        case_tasks_serializer = InterfaceTaskSerializer(page_api_tasks, many=True)
        return pg.get_paginated_response(case_tasks_serializer.data)
class Login(APIView):
    '''
    API endpoint that allows user to login
    '''
    permission_classes = (AllowAny, )
    schema = schemas.ManualSchema(fields=[
        coreapi.Field("username",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("password",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
    ])

    def post(self, request):
        # print(self.schema["usernname"])
        username = request.data.get('username')
        password = request.data.get('password')
        if username is None or password is None:
            return Response(
                {'error': 'Please provide both username and password'},
                status=HTTP_400_BAD_REQUEST)
        user = authenticate(username=username, password=password)
        print(username, password)
        if not user:
            return Response({'error': 'Invalid Credentials'},
                            status=HTTP_404_NOT_FOUND)
        token, _ = Token.objects.get_or_create(user=user)
        return Response({'token': token.key}, status=200)
Exemple #5
0
    def get_serializer_fields(self, path, method, view):
        fields = super(CustomSchemaGenerator, self).get_serializer_fields(path, method, view)

        body_fields_absent = True if len(fields) == 0 and method in ('PUT', 'PATCH', 'POST') else False

        try:
            for param in view.query_params:
                field = coreapi.Field(
                    name=param['name'],
                    location='query',  # form
                    required=param['required'],
                    schema=coreschema.String())
                fields.append(field)
        except AttributeError:
            pass

        if body_fields_absent:
            field = coreapi.Field(
                name='data',
                location='body',  # form
                required=True,
                schema=coreschema.String())
            fields.append(field)

        return fields
Exemple #6
0
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})
Exemple #7
0
class HashtagAPIView(APIView):
    """
    A simple APIView for querying hashtags
    """
    schema = AutoSchema(manual_fields=[
        coreapi.Field("query",
                      required=True,
                      location="path",
                      schema=coreschema.String(
                          title="query",
                          description="Query string to search for tweets.",
                      )),
        coreapi.Field("limit",
                      required=False,
                      location="query",
                      schema=coreschema.String(
                          title="limit",
                          description="Define result count",
                      )),
    ])
    permission_classes = (permissions.AllowAny, )

    def get(self, request, *args, **kwargs):
        try:
            query = kwargs.get('query')
            limit = request.GET.get('limit', 30)
            results = tweet_api.search_tweets_data(
                query,
                limit,
            )
            return Response(results, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'error': "Something went wrong."},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Exemple #8
0
 def get_schema_fields(self, view):
     super().get_schema_fields(view)
     search_field = getattr(view, 'date_search_field', None)
     return [
         coreapi.Field(
             name='date_from',
             required=False,
             location='query',
             schema=coreschema.String(
                 title="Begin date",
                 description=f"Begin date for {search_field}",
                 pattern='[0-9]{4}-[0-9]{2}-[0-9]{2}',
             ),
         ),
         coreapi.Field(
             name='date_to',
             required=False,
             location='query',
             schema=coreschema.String(
                 title="End date",
                 description=f"End date for {search_field}",
                 pattern='[0-9]{4}-[0-9]{2}-[0-9]{2}',
             ),
         ),
     ]
Exemple #9
0
class DumpFixtureAPIView(generics.CreateAPIView):
    permission_classes = (SuperuserRequiredPermission, )
    schema = schemas.ManualSchema(fields=[
        coreapi.Field("app_name",
                      required=True,
                      location="form",
                      schema=coreschema.String(max_length=10)),
        coreapi.Field("model_name",
                      required=True,
                      location="form",
                      schema=coreschema.String(max_length=50)),
        coreapi.Field("filter_options",
                      required=False,
                      location="form",
                      schema=coreschema.Object()),
        coreapi.Field("file_name",
                      required=True,
                      location="form",
                      schema=coreschema.String(max_length=50)),
    ])

    def post(self, request, *args, **kwargs):
        """
        Download model fixture
        """
        serializer = DumpFixtureSerializer(data=request.data)
        if not serializer.is_valid():
            return Response('Data is not valid')
        form_data = serializer.data
        file_name = form_data.pop('file_name')
        json_data = get_model_fixture_dump(**form_data)
        return download(json_data, file_name)
Exemple #10
0
 def get_schema_fields(self, view):
     return (
         Field(
             name='period',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("Period"),
                 description=
                 _('Period of occupancy. Month numbers (1-12) separated by comas.'
                   ' any = occupied at any time in the year. ignore = occupied or not.'
                   ' Example: 7,8 for july and august'))),
         Field(name='practices',
               required=False,
               location='query',
               schema=coreschema.String(
                   title=_("Practices"),
                   description=_(
                       'Practices ids separated by comas. Example: 1,3'))),
         Field(name='structure',
               required=False,
               location='query',
               schema=coreschema.Integer(
                   title=_("Structure"),
                   description=_('Structure id. Example: 5'))),
     )
Exemple #11
0
    def __init__(self, manual_fields=None):
        if manual_fields is None:
            manual_fields = []

        manual_fields += [
            coreapi.Field("username",
                          required=True,
                          location="form",
                          schema=coreschema.String(
                              title='username',
                              description='The username for the user.')),
            coreapi.Field("email",
                          required=True,
                          location="form",
                          schema=coreschema.String(
                              title='email',
                              description='The email for the user.')),
            coreapi.Field("password",
                          required=True,
                          location="form",
                          schema=coreschema.String(
                              title='password',
                              description='The password for the user.')),
        ]

        super().__init__(manual_fields=manual_fields)
Exemple #12
0
 def coreapi_schema(self):
     if self.request.method == 'GET':
         fields = [
             coreapi.Field("name",
                           required=False,
                           location="query",
                           schema=coreschema.String(max_length=30)),
             coreapi.Field("name_contains",
                           required=False,
                           location="query",
                           schema=coreschema.String(max_length=30))
         ]
     elif self.request.method == 'POST':
         fields = [
             coreapi.Field("params",
                           required=True,
                           location="body",
                           schema=coreschema.Object())
         ]
     else:
         fields = [
             coreapi.Field("name",
                           required=True,
                           location="body",
                           schema=coreschema.String(max_length=30))
         ]
     return schemas.ManualSchema(fields=fields)
Exemple #13
0
class RegisterView(APIView):
    Schema = AutoSchema(manual_fields=[
        coreapi.Field(name="username", required=True, location="form", schema=coreschema.String(description='用户名')),
        coreapi.Field(name="password", required=True, location="form", schema=coreschema.String(description='密码')),
        coreapi.Field(name="email", required=True, location="form", schema=coreschema.String(description='邮箱地址')),
    ])
    schema = Schema

    def post(self, request):
        '''
        【用户注册】
        '''

        email = request.data.get('email', None)
        username = request.data.get('username', None)
        password = request.data.get('password', None)

        if not all([email, username, password]):
            response = ResponseCode.REQUEST_DATA_ERROR.value
        elif not re.match(r'^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$', email):
            response = ResponseCode.REQUEST_DATA_ERROR.value
        elif not re.match(r'[\u4e00-\u9fa5_a-zA-Z0-9_]{2,10}', username):
            response = ResponseCode.REQUEST_DATA_ERROR.value
        elif len(password) < 6:
            response = ResponseCode.REQUEST_DATA_ERROR.value
        else:
            if User.objects.filter(email=email).first():
                response = ResponseCode.IDENTITY_EXISTED.value
            else:
                user = User.objects.create(username=username, email=email, is_active=True)
                user.set_password(password)
                user.save()
                response = ResponseCode.HANDLE_SUCCESS.value
        return Response(response)
Exemple #14
0
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({})

    '''
 def __init__(self):
     manual_fields = [
         coreapi.Field(
             name="email",
             required=True,
             location="body",
             schema=coreschema.String(
                 title="Email",
                 description="Valid email for authentication"),
         ),
         coreapi.Field(
             name="firstName",
             required=True,
             location="body",
             schema=coreschema.String(title="First Name",
                                      description="First name"),
         ),
         coreapi.Field(
             name="lastName",
             required=True,
             location="body",
             schema=coreschema.String(title="Last Name",
                                      description="Last name"),
         ),
     ]
     super().__init__(fields=manual_fields, encoding="application/json")
Exemple #16
0
 def get_serializer_fields(self, path, method):
     fields = []
     if method == 'POST':
         fields = [
             coreapi.Field(name='name',
                           required=False,
                           location="form",
                           schema=coreschema.String(title='name',
                                                    default=None,
                                                    description='name'),
                           description='name'),
             coreapi.Field(name='source',
                           required=True,
                           location="form",
                           schema=coreschema.String(title='source',
                                                    default=None,
                                                    description='source'),
                           description='source'),
             coreapi.Field(name='details',
                           required=True,
                           location="form",
                           schema=coreschema.String(title='details',
                                                    default=None,
                                                    description='details'),
                           description='details'),
             coreapi.Field(name='summ',
                           required=True,
                           location="form",
                           schema=coreschema.Integer(title='summ',
                                                     default=None,
                                                     description='summ'),
                           description='summ'),
         ]
     return fields
 def get_param_fields(self, view):
     return [
         coreapi.Field(
             name='year_month_day',
             required=True,
             location='query',
             schema=coreschema.String(
                 description='Year/Month/Day of birth format as : yyyy/mm/dd'
             ),
         ),
         coreapi.Field(
             name='hour_min',
             required=True,
             location='query',
             schema=coreschema.String(
                 description='Hour:Minute of birth format as : hh:mm'),
         ),
         coreapi.Field(
             name='lat',
             required=True,
             location='query',
             schema=coreschema.String(description='Latitude of birth'),
         ),
         coreapi.Field(
             name='lng',
             required=True,
             location='query',
             schema=coreschema.String(description='Longitude of birth'),
         ),
     ]
Exemple #18
0
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
Exemple #19
0
class HistoryViewset(viewsets.GenericViewSet, mixins.ListModelMixin,
                     mixins.RetrieveModelMixin):
    """
    允许查看当前用户的历史数据 API路径
    """
    serializer_class = HistorySerializer
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, )
    ordering_fields = ('created_at', )
    pagination_class = MyAllpagination

    def get_queryset(self):
        config_obj = Config.objects.filter(user=self.request.user)
        return config_obj

    @action(methods=['post'],
            detail=False,
            schema=AutoSchema(manual_fields=[
                coreapi.Field('itemids',
                              required=False,
                              location='query',
                              schema=coreschema.String(description='item数组')),
                coreapi.Field('time_from',
                              required=False,
                              location='query',
                              schema=coreschema.String(
                                  description='开始时间戳, 默认为前60分钟的时间戳')),
                coreapi.Field('time_till',
                              required=False,
                              location='query',
                              schema=coreschema.String(
                                  description='结束时间戳, 默认为当前时间戳'))
            ]))
    def loadtime(self, request, *args, **kwargs):
        """
        监控项历史数据,单位秒
        """
        time_from = request.data.get('time_from',
                                     int(time() // 60 * 60) - 3600)
        time_till = request.data.get('time_till')
        itemids = json.loads(request.data.get('itemids'))
        params = {
            'itemids': itemids,
            'time_from': time_from,
            'history': 0,
            'output': ['clock', 'value', 'itemid']
        }
        if time_till:
            params['time_till'] = time_till
        history = ZBXClient.history.get(**params)
        data_generator = map(
            lambda x: {
                'itemid': int(x['itemid']),
                'time': int(x['clock']),
                'value': float(x['value'])
            }, history)
        data = [d for d in data_generator]
        return Response(data)
Exemple #20
0
class ObtainTemporaryAuthToken(ObtainAuthToken):
    """
    post:
    Create a temporary token used to connect to the API.
    """
    model = TemporaryToken
    parser_classes = (JSONParser, )
    if coreapi is not None and coreschema is not None:
        schema = ManualSchema(
            fields=[
                coreapi.Field(
                    name="login",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Login",
                        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 get_serializer(self):
        return AuthTokenSerializer()

    def post(self, request):
        CONFIG = settings.REST_FRAMEWORK_TEMPORARY_TOKENS
        serializer = serializers.CustomAuthTokenSerializer(
            data=request.data,
            context={'request': request},
        )
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token = None

        token, _created = TemporaryToken.objects.get_or_create(user=user)

        if token.expired:
            # If the token is expired, generate a new one.
            token.delete()
            expires = timezone.now() + timezone.timedelta(
                minutes=CONFIG['MINUTES'])

            token = TemporaryToken.objects.create(user=user, expires=expires)

        data = {'token': token.key}
        return Response(data)
Exemple #21
0
class EnsemblFeature(mixins.CreateModelMixin, generics.GenericAPIView):

    permission_classes = (IsAuthenticated, )
    serializer_class = EnsemblGeneSerializer
    schema = ManualSchema(
        description=
        "Bulk load/update of genes and their transcript from an Ensembl release",
        fields=[
            coreapi.Field(name="species",
                          required=True,
                          location="path",
                          schema=coreschema.String(),
                          description="Species scientific name"),
            coreapi.Field(name="assembly_accession",
                          required=True,
                          location="path",
                          schema=coreschema.String(),
                          description="Assembly accession"),
            coreapi.Field(name="ensembl_tax_id",
                          required=True,
                          location="path",
                          schema=coreschema.Integer(),
                          description="Species taxonomy id"),
            coreapi.Field(name="ensembl_release",
                          required=True,
                          location="path",
                          schema=coreschema.Integer(),
                          description="Ensembl release number"),
        ])

    def get_serializer(self, *args, **kwargs):
        """
        method should have been passed request.data as 'data' keyword argument
        assert "data" in kwargs, (
            "data not present"
        )
        # data should come as a list of feature-like items
        assert isinstance(kwargs["data"], list), (
            "data is not a list"
        )

        when a serializer is instantiated and many=True is passed,
        a ListSerializer instance will be created. The serializer
        class then becomes a child of the parent ListSerializer
        """
        kwargs["many"] = True

        return super(EnsemblFeature, self).get_serializer(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        """
        this calls self.perform_create(self.get_serializer)
        """
        self.create(request, *args, **kwargs)

        return Response({'success': 1}, status=status.HTTP_201_CREATED)
class ActuatorAccess(APIView):
    """
    API endpoint that allows users actuator access to be viewed or edited.
    """
    permission_classes = (permissions.IsAdminUser, )

    schema = utils.OrcSchema(manual_fields=[
        coreapi.Field(
            "username",
            required=True,
            location="path",
            schema=coreschema.String(
                description='Username to list the accessible actuators'))
    ],
                             put_fields=[
                                 coreapi.Field("actuators",
                                               required=True,
                                               location="body",
                                               schema=coreschema.Array(
                                                   items=coreschema.String(),
                                                   min_items=1,
                                                   unique_items=True))
                             ])

    def get(self, request, username, *args, **kwargs):  # pylint: disable=unused-argument
        """
        API endpoint that lists the actuators a users can access
        """
        username = bleach.clean(username)
        rtn = [
            g.name for g in ActuatorGroup.objects.filter(
                users__in=[User.objects.get(username=username)])
        ]
        return Response(rtn)

    def put(self, request, username, *args, **kwargs):  # pylint: disable=unused-argument
        """
        API endpoint that adds actuators to a users access
        """
        username = bleach.clean(username)
        user = User.objects.get(username=username)
        if user is None:
            return ParseError(detail='User cannot be found', code=404)

        rtn = []
        for actuator in request.data.get('actuators', []):
            actuator = bleach.clean(actuator)

            group = Group.objects.exclude(actuatorgroup__isnull=True).filter(
                name=actuator).first()
            if group:
                rtn.append(group.name)
                user.groups.add(group)

        return Response(rtn)
Exemple #23
0
 def get_schema_fields(self, view):
     return [
         coreapi.Field("position_type",
                       required=True,
                       location="path",
                       schema=coreschema.String()),
         coreapi.Field("position_sub_type",
                       required=False,
                       location="path",
                       schema=coreschema.String()),
     ]
Exemple #24
0
    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
Exemple #25
0
class QuestionRamdomList(APIView):
    schema = ManualSchema(fields=[
        coreapi.Field("position_type",
                      required=True,
                      location="path",
                      schema=coreschema.String()),
        coreapi.Field("position_sub_type",
                      required=False,
                      location="path",
                      schema=coreschema.String()),
    ])
    # filter_backends = (SimpleFilterBackend,)
    """
    Retrieve 5 questions randomly.
    """
    def get(self, request, format=None):
        try:
            position_type = request.query_params.get(
                'position_type')  #request.query_params.get('position_type')
            position_sub_type = request.query_params.get(
                'position_sub_type'
            )  #request.query_params.get('position_type')

            if not position_type:
                questions = Question.objects.all()
            else:
                position_type = PositionType.objects.get(
                    name__iexact=position_type)
                if not position_sub_type:
                    print('===== filter question: ', position_type.id)
                    questions = Question.objects.filter(
                        position_type=position_type.id)
                else:
                    questions = Question.objects.filter(
                        position_type=position_type.id).filter(
                            position_sub_type=position_sub_type)
        except PositionType.DoesNotExist:
            raise Http404

        if len(questions) > 5:
            # generate random numbers
            randnums = random.sample(range(len(questions)), 5)

            # create new question list with the random numbers
            random_questions = []
            for index in randnums:
                random_questions.append(questions[index])

            serializer = QuestionSerializer(random_questions, many=True)
            return Response(serializer.data)
        else:
            serializer = QuestionSerializer(questions, many=True)
            return Response(serializer.data)
Exemple #26
0
    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
Exemple #27
0
class GovernmentDetailView(APIView):
    """
    Return details about a particular government
    """
    schema = AutoSchema(manual_fields=[
        coreapi.Field('govid',
                      required=True,
                      location='path',
                      schema=coreschema.String(
                          description='Unique identifier for a gorvernment')),
        coreapi.Field('year',
                      required=False,
                      location='query',
                      schema=coreschema.String(description='year')),
    ])

    def get(self, request, govid):
        year = request.query_params.get('year',
                                        Yearref.objects.latest('yearid').yr)
        query = Gov.objects.get(govid=govid)
        serialize = serializers.GovernmentDetailSerializer(
            query, context={'request': request})
        population = Govindicator\
                         .objects\
                         .only('iid__name', 'value', 'iid__short_name')\
                         .filter(
                             govid=govid,
                             iid__parentgid=1116,
                             yearid__yr=year
                         ).select_related('iid')

        household = Govindicator\
                    .objects\
                    .only('iid__name', 'value', 'iid__short_name')\
                    .filter(
                            govid=govid,
                            iid__parentgid=1119,
                            yearid__yr=year
                    ).select_related('iid')

        pop_density, total_population, area = averages.density(population)
        house_density, _, _ = averages.density(household)
        return Response({
            'details': serialize.data,
            'overview': {
                'Households/km': house_density,
                'People/km': pop_density,
                'Population': total_population,
                'Area': area,
            },
            'year': year
        })
Exemple #28
0
class GovernmentRankingView(APIView):
    """
    Return the mandate indicator rankings for a particular government

    """
    schema = AutoSchema(manual_fields=[
        coreapi.Field('govid',
                      required=True,
                      location='path',
                      schema=coreschema.String(
                          description='Unique identifier for gorvernment')),
        coreapi.Field('year',
                      required=False,
                      location='query',
                      schema=coreschema.String(
                          description='full year of ranking eg: 2016'))
    ])

    def get(self, request, govid):
        year = request.query_params.get('year', None)
        try:
            if year:
                int(year)
                query = Govrank.objects.filter(
                    govid_id=govid,
                    yearid__yr=year,
                ).select_related('govid', 'yearid')
            else:
                query = Govrank.objects\
                               .filter(govid_id=govid)\
                               .select_related('govid', 'yearid')
        except Govrank.DoesNotExist:
            raise exceptions.NotFound()
        except ValueError:
            raise exceptions.ParseError()
        else:
            category = Gov.objects\
                          .only('gcid')\
                          .get(govid=govid)
            ranking_total = Gov.objects.filter(gcid=category.gcid).count()
            serialize = serializers.GovernmentRankingSerializer(
                query,
                context={
                    'request': request,
                    'ranking_total': ranking_total
                },
                many=True)

            return Response({
                'results': serialize.data,
                'ranking_out_of': ranking_total
            })
Exemple #29
0
def get_record_schema():
    """
    Generates a ManualSchema for RecordCreate view
    """
    record_schema = schemas.ManualSchema(
        fields=[
            coreapi.Field(
                "call_id",
                required=True,
                location="form",
                schema=coreschema.String(
                    description='Unique for each call record pair'
                ),
            ),
            coreapi.Field(
                "type",
                required=True,
                location="form",
                schema=coreschema.String(
                    description='Indicate if it\'s a call start or end record'
                )
            ),
            coreapi.Field(
                "timestamp",
                required=True,
                location="form",
                schema=coreschema.String(
                    description='The timestamp of when the event occurred'
                )
            ),
            coreapi.Field(
                "source",
                required=False,
                location="form",
                schema=coreschema.String(
                    description='The subscriber phone number that originated '
                                'the call'
                )
            ),
            coreapi.Field(
                "destination",
                required=False,
                location="form",
                schema=coreschema.String(
                    description='The phone number receiving the call'
                )
            ),
        ],
        encoding="application/json",
    )

    return record_schema
class RegisterUser(APIView):
    ''' 
    API endpoint that allows user to register a new user
    username: '******'
    first name: ' enter the first name '
    last name: ' enter the last name '
    password1: ' enter the password ' 
    password2: ' enter the password again ' 
    '''
    schema = schemas.ManualSchema(fields=[
        coreapi.Field("username",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("first_name",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("last_name",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("password1",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
        coreapi.Field("password2",
                      required=True,
                      location="form",
                      schema=coreschema.String()),
    ])
    permission_classes = (AllowAny, )

    def post(self, request):
        username = request.data.get('username')
        first_name = request.data.get('first_name')
        last_name = request.data.get('last_name')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        if password1 == password2:
            # user.password = password1
            user = User.objects.create_user(username, None, password1)
            user.first_name = first_name
            user.last_name = last_name
            try:
                user.save()
                return Response('user created')
            except:
                return Response('User already exists')
        else:
            return Response('please check the password')