Beispiel #1
0
class TransferRecipientSerializer(serializers.Serializer):
    type = serializers.Serializer(required=True)
    name = serializers.Serializer(required=True)
    account_number = serializers.CharField(required=True)
    bank_code = serializers.CharField(required=True)
    description = serializers.CharField(required=False)
    currency = serializers.CharField(required=False)
    authorization_code = serializers.CharField(required=False)
    metadata = serializers.JSONField(required=False)
Beispiel #2
0
def test_instance_validator_serializer():
    validator = InstanceValidator()
    serializer = serializers.Serializer()
    validator.set_context(serializer)

    assert validator.serializer == serializer
    assert validator.serializer.instance is None
Beispiel #3
0
    def get_meta_serializer(self):
        default_serializer = serializers.Serializer(read_only=True)
        if isinstance(self.instance, Ticket):
            _type = self.instance.type
        else:
            _type = self.context['request'].query_params.get('type')

        if _type:
            action_serializer_classes_mapping = type_serializer_classes_mapping.get(
                _type)
            if action_serializer_classes_mapping:
                query_action = self.context['request'].query_params.get(
                    'action')
                action = query_action if query_action else self.context[
                    'view'].action
                serializer_class = action_serializer_classes_mapping.get(
                    action)
                if not serializer_class:
                    serializer_class = action_serializer_classes_mapping.get(
                        'default')
            else:
                serializer_class = default_serializer
        else:
            serializer_class = default_serializer

        if not serializer_class:
            serializer_class = default_serializer

        if isinstance(serializer_class, type):
            serializer = serializer_class()
        else:
            serializer = serializer_class

        return serializer
Beispiel #4
0
    def get_attrs_serializer(self):
        default_serializer = serializers.Serializer(read_only=True)
        if isinstance(self.instance, models.Application):
            _type = self.instance.type
            _category = self.instance.category
        else:
            _type = self.context['request'].query_params.get('type')
            _category = self.context['request'].query_params.get('category')

        if _type:
            serializer_class = type_serializer_classes_mapping.get(_type)
        elif _category:
            serializer_class = category_serializer_classes_mapping.get(
                _category)
        else:
            serializer_class = default_serializer

        if not serializer_class:
            serializer_class = default_serializer

        if isinstance(serializer_class, type):
            serializer = serializer_class()
        else:
            serializer = serializer_class
        return serializer
Beispiel #5
0
def test_instance_validator_serializer_instance():
    validator = InstanceValidator()
    instance = object()
    serializer = serializers.Serializer(instance=instance)
    validator.set_context(serializer)
    assert validator.serializer == serializer
    assert validator.serializer.instance == serializer.instance
Beispiel #6
0
def api(request):
    print("req", request)
    queryset = Companies.objects.all()
    print("queryset", queryset)
    companies = Companies.objects.all().order_by('name')
    json = serializers.Serializer('json', companies)
    return HttpResponse(json)
Beispiel #7
0
    def __call__(self, data, strict_mode=False):
        if self.VALIDATE_FIELD_NAME not in data:
            return data
        parameters_data = data[self.VALIDATE_FIELD_NAME]
        operation_type_pk = data.get(self.OPERATION_MODEL_TYPE_FIELD)
        if operation_type_pk is None:
            self.fail(f'{self.OPERATION_MODEL_TYPE_FIELD} field is required')

        parameters = self.parameter_model.objects.all_active(
            **{self.PARAMETER_MODEL_TYPE_FIELD: operation_type_pk})
        parameters_serializer = serializers.Serializer(data=parameters_data)
        for param in parameters:
            parameters_serializer.fields[param.code] = self.get_field_by_param(
                param)
        if not parameters_serializer.is_valid():
            self.fail(data=parameters_serializer.errors)
        if strict_mode:
            unexpected_data = set(parameters_serializer.initial_data) - set(
                parameters_serializer.data)
            # unexpected_data = {key: val for key, val in parameters_serializer.initial_data
            #                                 if key not in parameters_serializer.data}
            if unexpected_data:
                self.fail(f'unexpected keywords {unexpected_data}')

        data[self.VALIDATE_FIELD_NAME] = parameters_serializer.data
        return data
Beispiel #8
0
def get_photo(request):
    # create data dictionary
    # picture = Picture.objects.get(pk=picture_id)
    all_picture = Picture.objects.filter(public=False)[:10]
    data = serializers.Serializer('json', all_picture)

    # dataJSON = MedicSerializer(all_picture, many=True)
    return render(request, 'portfolio/carouselv2.html', {'data': data})
Beispiel #9
0
    def test_field_value_null(self):
        request = Request(self.factory.get('/', {'lang': 'en-US'}))
        mock_serializer = serializers.Serializer(context={'request': request})

        field = self.field_class()
        self.addon.description_translations = {'en-US': None}
        field.bind('description', mock_serializer)
        result = field.to_representation(field.get_attribute(self.addon))
        assert result is None
Beispiel #10
0
def test_is_field():
    assert is_field(serializers.SlugField)
    assert is_field(serializers.SlugField())

    assert not is_field(models.CharField)
    assert not is_field(models.CharField())

    assert not is_field(serializers.Serializer)
    assert not is_field(serializers.Serializer())
 def inline_serializer_from_fields(self, fields_dict, sub_serializer=True):
     attrs = {
         f_name: copy.deepcopy(field)
         for f_name, field in fields_dict.items()
     }
     serializer = type('Attributes', (serializers.Serializer, ), attrs)()
     if sub_serializer:
         serializer.bind(field_name='', parent=serializers.Serializer())
     return serializer
Beispiel #12
0
class PetSerializer(serializers.Serializer):
    self = serializers.SerializerMethodField('create_self')
    id = serializers.CharField()
    images = serializers.Serializer(many=True)
    user_description = serializers.CharField()
    breed_by_user = serializers.CharField()
    created_at = serializers.DateTimeField()

    def create_self(self, pet):
        return urlresolvers.reverse('pets_view', kwargs=dict(id=str(pet.id)))
Beispiel #13
0
    def list(self, request):
        serializer_data = datetime.now().second % 10
        print(serializer_data)
        serializer = serializers.Serializer({"value":serializer_data})
        stat = status.HTTP_200_OK
        print(serializer.data)
        if serializer_data%10 ==0:
            stat = status.HTTP_503_SERVICE_UNAVAILABLE

        return Response({
            'tags': serializer_data,
        }, status=stat)
Beispiel #14
0
 def test_get_attribute_request_GET_lang(self):
     """
     Pass a lang in the query string, expect to have a single string
     returned instead of an object.
     """
     # Note that we don't go through the middlewares etc so the actual
     # language for the process isn't changed, we don't care as
     # _expect_single_string() method simply tests with the current
     # language, whatever it is.
     request = Request(self.factory.get('/', {'lang': 'lol'}))
     assert request.GET['lang'] == 'lol'
     mock_serializer = serializers.Serializer(context={'request': request})
     field = self.field_class()
     self._test_expected_single_string(field, mock_serializer)
Beispiel #15
0
class LifeDataViewSet(GenericViewSet):
    queryset = LifeData.objects.all()
    serializer_class = LifeDataSerializer
    permission_classes = []
    authentication_classes = []
    lookup_field = "external_id"

    @swagger_auto_schema(method="post",
                         request_body=serializers.Serializer(),
                         responses={204: "Success"})
    @action(detail=True, methods=["POST"])
    def downvote(self, request, *args, **kwargs):
        if not validatecaptcha(request):
            raise CaptchaRequiredException
        external_id = kwargs["external_id"]
        try:
            LifeData.objects.filter(external_id=external_id).update(
                downvotes=F("downvotes") + 1)
        except:
            pass

        return Response(status=status.HTTP_204_NO_CONTENT)

    @swagger_auto_schema(method="post",
                         request_body=serializers.Serializer(),
                         responses={204: "Success"})
    @action(detail=True, methods=["POST"])
    def upvote(self, request, *args, **kwargs):
        if not validatecaptcha(request):
            raise CaptchaRequiredException
        external_id = kwargs["external_id"]
        try:
            LifeData.objects.filter(external_id=external_id).update(
                upvotes=F("upvotes") + 1)
        except:
            pass
        return Response(status=status.HTTP_204_NO_CONTENT)
Beispiel #16
0
    def test_field_value_null(self):
        self.addon = addon_factory(slug='lol', name=None, description=None)

        request = Request(self.factory.get('/', {'lang': 'en-US'}))
        mock_serializer = serializers.Serializer(context={'request': request})
        field = self.field_class()

        field.bind('name', mock_serializer)
        result = field.to_representation(field.get_attribute(self.addon))
        assert result is None

        field.source = None
        field.bind('description', mock_serializer)
        result = field.to_representation(field.get_attribute(self.addon))
        assert result is None
Beispiel #17
0
class PetCreationSerializer(serializers.Serializer):
    images = serializers.Serializer(many=True, required=False)
    # geo point (latitude, longitude)
    position = CoordinatesSerializer()
    phone_number = serializers.CharField()
    user_description = serializers.CharField(required=False)
    breed_by_user = serializers.CharField()

    def validate_images(self, attrs, field_name):
        if not field_name in attrs:
            return attrs
        for filename in attrs[field_name]:
            full_path = os.path.join(settings.MEDIA_ROOT, filename)
            if not os.path.exists(full_path):
                raise serializers.ValidationError(
                    'File "{0}" does not exist'.format(filename)
                )
        return attrs
Beispiel #18
0
 def test_get_attribute_request_GET_lang(self):
     """
     Pass a lang in the query string, expect to have a single string
     returned instead of an object.
     """
     # We don't go through the middlewares etc where the language for the
     # process would be set, so we have to manually activate the correct
     # locale.
     request = Request(self.factory.get('/', {'lang': 'es'}))
     assert request.GET['lang'] == 'es'
     mock_serializer = serializers.Serializer(context={'request': request})
     with self.activate('es'):
         if self.addon.id:
             # Reload so the transformer loads the translation in the
             # correct locale.
             # (But only if it's in the database - the ES test doesn't save)
             self.addon = self.addon.reload()
         field = self.field_class()
         self._test_expected_single_locale(field, mock_serializer)
Beispiel #19
0
    def get_meta_serializer(self):
        default_serializer = serializers.Serializer(read_only=True)

        if isinstance(self.instance, self.__class__.Meta.model):
            _type = self.instance.type
        else:
            _type = self.context['request'].query_params.get('type')

        if _type:
            serializer_class = self.storage_type_serializer_classes_mapping.get(_type)
        else:
            serializer_class = default_serializer

        if not serializer_class:
            serializer_class = default_serializer

        if isinstance(serializer_class, type):
            serializer = serializer_class()
        else:
            serializer = serializer_class
        return serializer
 def get_serializer(self):
     assert hasattr(self.request, 'versioning_scheme')
     return serializers.Serializer()
Beispiel #21
0
def test_instance_validator_validation_serializer_error():
    validator = InstanceValidator()
    validator.set_context(serializers.Serializer())

    with pytest.raises(serializers.ValidationError):
        validator.raise_validation_error({'foo': 'bar'})
Beispiel #22
0
class CeleryTaskResultSerializer(ParamsSerializer):
    query_id = s.Serializer(label=_('任务查询ID'), required=False)
Beispiel #23
0
class LikeSerializer(serializers.Serializer):
    pk = serializers.Serializer()

    class Meta:
        fields = ('pk')
Beispiel #24
0
            openapi.Schema(
                description="[min, max] values for land cover filter",
                type=openapi.TYPE_ARRAY,
                items=openapi.Items(type=openapi.TYPE_INTEGER)),
            'fertility capability classification':
            openapi.Schema(
                description=
                "[min, max] values for fertility capability classification filter",
                type=openapi.TYPE_ARRAY,
                items=openapi.Items(type=openapi.TYPE_INTEGER)),
        }),
    responses={
        status.HTTP_200_OK:
        serializers.Serializer({
            "Bounds": {},
            "Grid": {
                "FeatureCollection": "..."
            }
        })
    },
)
@api_view(['POST'])
def wider_area(request):
    """Get all or fitlered wider area.
    """
    serializer_data, user = verify_auth_token(request)
    if not serializer_data or user["paymentLevels"] != "SECOND LEVEL" or user[
            "memberOf"] != "61164207eaef91000adcfeab":
        return Response({"Error": "Unauthorized request"},
                        status=status.HTTP_403_FORBIDDEN)

    # NOTE: To be used for storing creds, the memberOf id I mean
Beispiel #25
0
 def test_field_get_attribute_request_POST(self):
     request = Request(self.factory.post('/'))
     mock_serializer = serializers.Serializer()
     mock_serializer.context = {'request': request}
     field = self.field_class()
     self._test_expected_dict(field)
Beispiel #26
0
 def setUp(self):
     self.expected_college = College(name="cbit",
                                     location="Hyderabad",
                                     acronym="cbit",
                                     contact="*****@*****.**")
     self.serialized_obj = serializers.Serializer(self.expected_college)
Beispiel #27
0
class PrinterViewSet(viewsets.ModelViewSet):
    queryset = Printer.objects.all()
    serializer_class = PrinterSerializer
    filter_backends = (django_filters.rest_framework.DjangoFilterBackend, )
    filterset_fields = (
        "name",
        "build_volume",
        "printer_type",
        "is_printing",
        "is_paused",
        "number_of_extruders",
        "has_heated_chamber",
    )

    @swagger_auto_schema(request_body=GCODECommandSerializer)
    @action(detail=True, methods=["post"])
    def gcode_command(self, request, pk=None):
        """
        Endpoint that accepts the ID of the printer and list of commands
        NOTE: The commands aren't escaped, so be wary when using this endpoint
        """

        serializer = GCODECommandSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        execute_gcode_commands(printer_id=pk, **serializer.validated_data)
        return Response(
            data={
                "printer_id": kwargs["printer_id"],
                "commands": kwargs["commands"]
            },
            status=status.HTTP_200_OK,
        )

    @swagger_auto_schema(request_body=DirectionSerializer)
    @action(detail=True, methods=["post"])
    def move_axis(self, request, pk=None):
        """
        Endpoint for moving around the tools of the printer,
        you can provide only one axis with one value
        or multiple as [x,z], [10,20]
        """

        serializer = DirectionSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        move_axis_printer(**serializer.validated_data,
                          printer_id=kwargs["printer_id"])
        return Response(data={**kwargs}, status=status.HTTP_200_OK)

    @swagger_auto_schema(request_body=JobSerializer)
    @action(detail=True, methods=["post"])
    def start_job(self, request, pk=None):
        """
        API endpoint for implicitly creating a one-file long queue,
        and therefore starting the print job
        # TODO this should send an exception if not ready to print
        NOTE: The print job won't start unless
        the printer is set as "ready to print"
        NOTE 2: If there is an existing queue, the file will be added to it
        """
        serializer = JobSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        printer_data = start_print_job(printer_id=pk,
                                       **serializer.validated_data)
        return Response(
            data={
                "status": "The job has been started successfully",
                "socket_connection_info": {
                    "ip": printer_data.ip_address,
                    "port": printer_data.port_number,
                    "endpoint": "/to/be/updated",
                },
            },
            status=status.HTTP_200_OK,
        )

    # I'm passing an empty serializers so that the docs don't confuse people
    # Passing an empty serializer instance makes yasg generate an
    # empty data body, required with POST request
    @swagger_auto_schema(request_body=serializers.Serializer())
    @action(detail=True, methods=["post"])
    def pause_current_job(self, request, pk=None):
        """
        API endpoint for pausing the current printing job.
        It can also be used to un-pause the job since it keeps the state
        """
        pause_print_job(printer_id=pk)
        return Response(
            data={"status": "The job has been successfully paused"},
            status=status.HTTP_200_OK,
        )

    @swagger_auto_schema(request_body=serializers.Serializer())
    @action(detail=True, methods=["post"])
    def cancel_print_job(self, request, pk=None):
        """
        API endpoint for canceling the printing job.
        """
        cancel_print_job(**kwargs)
        return Response(
            data={"status": "The job has been canceled successfully"},
            status=status.HTTP_200_OK,
        )

    @swagger_auto_schema(request_body=PrinterTempSerializer)
    @action(detail=True, methods=["post"])
    def set_temperature(self, request, pk=None):
        """
        Endpoint for setting the temperature of either:
        tool, bed or the chamber
        """
        data = self.PrinterTempSerializer(data=request.data)
        data.is_valid(raise_exception=True)

        set_printer_temperature(printer_id=kwargs["printer_id"],
                                **data.validated_data)

        return Response(
            data={
                "status":
                """
                The temperature for the Bed has been successfully set to {temp}
                """.format(temp=data.validated_data["temperature"])
            },
            status=status.HTTP_200_OK,
        )

    @swagger_auto_schema(request_body=serializers.Serializer())
    @action(detail=True, methods=["post"])
    def next_job(self, request, pk=None):
        """
        API endpoint for letting the PrinterIO system know
        that it can safely issue next print job

        NOTE: this should be called by the frontend only when the user
        has been prompted that it is in fact safe to proceed
        """
        call_next_job(printer_id=pk)
        return Response(data={"status": "Started next job successfully"},
                        status=status.HTTP_200_OK)
Beispiel #28
0
 def test_get_attribute_request_GET(self):
     request = Request(self.factory.get('/'))
     mock_serializer = serializers.Serializer(context={'request': request})
     field = self.field_class()
     self._test_expected_dict(field, mock_serializer)
Beispiel #29
0
 def test_get_attribute_empty_context(self):
     mock_serializer = serializers.Serializer(context={})
     field = self.field_class()
     self._test_expected_dict(field, mock_serializer)
Beispiel #30
0
 def get_serializer(self, *args, **kwargs):
     # needed to avoid `'super' object has no attribute 'get_serializer'`
     # exception, raised in TokenAuthorizationMixin.get_serializer
     return serializers.Serializer(*args, **kwargs)