当前位置: 首页>>代码示例>>Python>>正文


Python serializers.Serializer方法代码示例

本文整理汇总了Python中rest_framework.serializers.Serializer方法的典型用法代码示例。如果您正苦于以下问题:Python serializers.Serializer方法的具体用法?Python serializers.Serializer怎么用?Python serializers.Serializer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rest_framework.serializers的用法示例。


在下文中一共展示了serializers.Serializer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: handle_invalid_fields

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def handle_invalid_fields(this, data):
    """Validate incoming data.

    The primary validation being done is ensuring the incoming data only
    contains known fields.

    Args:
        this    (Object): Serializer object
        data    (Dict): data to be validated
    Returns:
        (Dict): Validated data
    Raises:
        (ValidationError): if field inputs are invalid

    """
    unknown_keys = None
    if hasattr(this, "initial_data"):
        unknown_keys = set(this.initial_data.keys()) - set(this.fields.keys())

    if unknown_keys:
        error = {}
        for unknown_key in unknown_keys:
            error[unknown_key] = _("Unsupported parameter or invalid value")
        raise serializers.ValidationError(error)
    return data 
开发者ID:project-koku,项目名称:koku,代码行数:27,代码来源:serializers.py

示例2: get_serializer_class

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def get_serializer_class(self, **kwargs) -> Type[Serializer]:
        """
        Return the class to use for the serializer.
        Defaults to using `self.serializer_class`.

        You may want to override this if you need to provide different
        serializations depending on the incoming request.

        (Eg. admins get full serialization, others get basic serialization)
        """
        assert self.serializer_class is not None, (
            "'%s' should either include a `serializer_class` attribute, "
            "or override the `get_serializer_class()` method." % self.__class__.__name__
        )

        return self.serializer_class 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:18,代码来源:generics.py

示例3: save

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def save(self, *args, **kwargs):
        """Serializer save that address prefetch issues."""
        update = getattr(self, 'instance', None) is not None
        instance = super(
            WithDynamicSerializerMixin,
            self
        ).save(
            *args,
            **kwargs
        )
        view = self._context.get('view')
        if view and update:
            if int(DRF_VERSION[0]) <= 3 and int(DRF_VERSION[1]) < 5:
                # Reload the object on update
                # to get around prefetch cache issues
                # Fixed in DRF in 3.5.0
                instance = self.instance = view.get_object()
        return instance 
开发者ID:AltSchool,项目名称:dynamic-rest,代码行数:20,代码来源:serializers.py

示例4: test_char_field_error_content

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def test_char_field_error_content(self):
        # Too long string
        self.data_set['title'] = 'Too Long Title For Defined Serializer'
        s = run_is_valid(SnippetSerializer, data=self.data_set)
        code = settings.FRIENDLY_FIELD_ERRORS['CharField']['max_length']
        self.assertEqual(s.errors['errors'][0]['code'], code)
        self.assertEqual(s.errors['errors'][0]['field'], 'title')

        # Empty string
        self.data_set['title'] = ''
        s = run_is_valid(SnippetSerializer, data=self.data_set)
        code = settings.FRIENDLY_FIELD_ERRORS['CharField']['blank']
        self.assertEqual(s.errors['errors'][0]['code'], code)
        self.assertEqual(s.errors['errors'][0]['field'], 'title')

        # No data provided
        self.data_set.pop('title')
        s = run_is_valid(SnippetSerializer, data=self.data_set)
        code = settings.FRIENDLY_FIELD_ERRORS['CharField']['required']
        self.assertEqual(s.errors['errors'][0]['code'], code)
        self.assertEqual(s.errors['errors'][0]['field'], 'title') 
开发者ID:FutureMind,项目名称:drf-friendly-errors,代码行数:23,代码来源:test_serializers.py

示例5: test_pagination_multiple_datatypes

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def test_pagination_multiple_datatypes(self):
        req = self._get_request('/foo', {'limit': 10, 'offset': 20})
        qs1 = [{'id': i} for i in range(25)]
        qs2 = [{'name': i} for i in range(25)]

        class FakeSerializer1(serializers.Serializer):
            id = serializers.IntegerField()

        class FakeSerializer2(serializers.Serializer):
            name = serializers.IntegerField()

        resp = paginate_results(
            req, (qs1, FakeSerializer1), (qs2, FakeSerializer2))
        assert resp == {
            'count': 50,
            'next': 'http://nxt',
            'previous': 'http://prv',
            'results': (
                [{'id': 20+i} for i in range(5)] +
                [{'name': i} for i in range(5)]
            )
        } 
开发者ID:Cadasta,项目名称:cadasta-platform,代码行数:24,代码来源:test_pagination.py

示例6: __init__

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def __init__(self, data=None, code=errors.SUCCESS, message=None,
                 template_name=None, headers=None, exception=False, content_type=None):
        super(Response, self).__init__(None, status=HTTP_200_OK)

        if isinstance(data, Serializer):
            msg = (
                'You passed a Serializer instance as data, but '
                'probably meant to pass serialized `.data` or '
                '`.error`. representation.'
            )
            raise AssertionError(msg)

        self.data = {'code': code,
                     'message': message if message else errors.MESSAGES.get(code, errors.UNKNOWN_ERROR),
                     'data': data}
        self.template_name = template_name
        self.exception = exception
        self.content_type = content_type

        if headers:
            for name, value in six.iteritems(headers):
                self[name] = value 
开发者ID:forcemain,项目名称:notes,代码行数:24,代码来源:response.py

示例7: get_paginator_serializer

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def get_paginator_serializer(self, view, child_serializer_class):
        class BaseFakeListSerializer(serializers.Serializer):
            results = child_serializer_class(many=True)

        class FakePrevNextListSerializer(BaseFakeListSerializer):
            next = URLField()
            previous = URLField()

        # Validate if the view has a pagination_class
        if not (hasattr(view, 'pagination_class')) or view.pagination_class is None:
            return BaseFakeListSerializer

        pager = view.pagination_class
        if hasattr(pager, 'default_pager'):
            # Must be a ProxyPagination
            pager = pager.default_pager

        if issubclass(pager, (PageNumberPagination, LimitOffsetPagination)):
            class FakeListSerializer(FakePrevNextListSerializer):
                count = IntegerField()
            return FakeListSerializer
        elif issubclass(pager, CursorPagination):
            return FakePrevNextListSerializer

        return BaseFakeListSerializer 
开发者ID:limdauto,项目名称:drf_openapi,代码行数:27,代码来源:entities.py

示例8: test_instance_is_updated_successfully_after_model_serializer_update

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def test_instance_is_updated_successfully_after_model_serializer_update(self):
        class Serializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
            class Meta:
                model = StringEnumeratedModel
                fiedls = ('enumeration', )

        instance = StringEnumeratedModel.objects.create(
            enumeration=CharTestEnum.FIRST
        )

        serializer = self.Serializer(data={'enumeration': 'second'})
        serializer.is_valid()

        serializer.update(instance, serializer.validated_data)
        instance.refresh_from_db()

        self.assertEqual(
            CharTestEnum.SECOND,
            instance.enumeration
        ) 
开发者ID:HackSoftware,项目名称:django-enum-choices,代码行数:22,代码来源:test_serializer_integrations.py

示例9: test_instance_is_created_successfully_when_using_custom_choice_builder

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def test_instance_is_created_successfully_when_using_custom_choice_builder(self):
        class Serializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
            class Meta:
                model = CustomChoiceBuilderEnumeratedModel
                fields = ('enumeration', )

        current_instance_count = CustomChoiceBuilderEnumeratedModel.objects.count()

        serializer = Serializer(data={'enumeration': 'Custom_first'})
        self.assertTrue(serializer.is_valid())

        instance = serializer.create(serializer.validated_data)

        self.assertEqual(
            current_instance_count + 1,
            CustomChoiceBuilderEnumeratedModel.objects.count()
        )
        self.assertEqual(
            CharTestEnum.FIRST,
            instance.enumeration
        ) 
开发者ID:HackSoftware,项目名称:django-enum-choices,代码行数:23,代码来源:test_serializer_integrations.py

示例10: benchmark

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def benchmark(serializer_fn, repetitions, num_objs=1, data=None):
    total_objs = repetitions * num_objs
    if not isinstance(serializer_fn, type):
        library = 'Marshmallow'
    elif issubclass(serializer_fn, serpy.Serializer):
        library = 'serpy'
    elif issubclass(serializer_fn, rf_serializers.Serializer):
        library = 'Django Rest Framework'
    print('Serializing {} objects using {}'.format(total_objs, library))

    if data is None:
        data = {}

    objs = [Obj(**data) for i in range(num_objs)]
    many = num_objs > 1
    if not many:
        objs = objs[0]

    t1 = time.time()
    for i in range(repetitions):
        serializer_fn(objs, many=many).data
    total_time = time.time() - t1
    print('Total time: {}'.format(total_time))
    print('Objs/s    : {}\n'.format(int(total_objs / total_time)))
    return total_time 
开发者ID:clarkduvall,项目名称:serpy,代码行数:27,代码来源:utils.py

示例11: drf_router

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def drf_router():
    """
    DRF Router as a lazy object because it needs to import User model which
    can't be done until after django.setup()
    """
    from django.contrib.auth.models import User
    from rest_framework import routers
    from rest_framework import serializers
    from rest_framework import viewsets

    class UserSerializer(serializers.Serializer):
        id = serializers.IntegerField(label="ID", read_only=True)
        username = serializers.CharField(max_length=200)

    class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer

    router = routers.SimpleRouter()
    router.register(r"users", UserViewSet)
    return router 
开发者ID:scoutapp,项目名称:scout_apm_python,代码行数:23,代码来源:django_app.py

示例12: test_describe_fields

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def test_describe_fields(self):
        class DummySerializer(serializers.Serializer):
            str = serializers.CharField()
            int = serializers.IntegerField()

        instance = DummySerializer()

        result = describe_serializer(instance, include_read_only=False)
        self.assertEqual(_flatten_field_data(result), {
            'str': {'value': 'string'},
            'int': {'value': 'int'}
        })

        result = describe_serializer(instance, include_read_only=True)
        self.assertEqual(_flatten_field_data(result), {
            'str': {'value': 'string'},
            'int': {'value': 'int'}
        }) 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:20,代码来源:tests.py

示例13: test_describe_field_with_complex_default

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def test_describe_field_with_complex_default(self):
        class DummyDefault(object):
            doc_format = 'some string format'

        class DummySerializer(serializers.Serializer):
            field = serializers.CharField(required=False, default=DummyDefault)

        instance = DummySerializer()
        result = describe_serializer(instance, include_read_only=False)
        self.assertEqual(_flatten_field_data(result), {
            'field': {
                'tags': 'optional, default="some string format"',
                'value': 'string'
            }
        })

        result = describe_serializer(instance, include_read_only=True)
        self.assertEqual(_flatten_field_data(result), {'field': {'value': 'string'}}) 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:20,代码来源:tests.py

示例14: test_describe_nested_serializer

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def test_describe_nested_serializer(self):
        class DummyNestedSerializer(serializers.Serializer):
            field = serializers.CharField()

        class DummySerializer(serializers.Serializer):
            top_level = DummyNestedSerializer()

        instance = DummySerializer()
        result = describe_serializer(instance, True)
        self.assertEqual(_flatten_field_data(result), {
            'top_level': {
                'value': {
                    'field': {'value': 'string'}
                }
            }
        }) 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:18,代码来源:tests.py

示例15: test_describe_nested_serializer_many

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import Serializer [as 别名]
def test_describe_nested_serializer_many(self):
        class DummyNestedSerializer(serializers.Serializer):
            field = serializers.CharField()

        class DummySerializer(serializers.Serializer):
            top_level = DummyNestedSerializer(many=True)

        instance = DummySerializer()
        result = describe_serializer(instance, True)
        self.assertEqual(_flatten_field_data(result), {
            'top_level': {
                'value': [{
                    'field': {'value': 'string'}
                }]
            }
        }) 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:18,代码来源:tests.py


注:本文中的rest_framework.serializers.Serializer方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。