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


Python serializers.BaseSerializer方法代码示例

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


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

示例1: __get_serializer_fields__

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import BaseSerializer [as 别名]
def __get_serializer_fields__(self, serializer):
        fields = []

        if hasattr(serializer, 'get_fields'):
            for key, field in serializer.get_fields().items():
                to_many_relation = True if hasattr(field, 'many') else False
                sub_fields = []

                if to_many_relation:
                    sub_fields = self.__get_serializer_fields__(field.child) if isinstance(field, BaseSerializer) else None
                else:
                    sub_fields = self.__get_serializer_fields__(field) if isinstance(field, BaseSerializer) else None

                fields.append({
                    "name": key,
                    "type": str(field.__class__.__name__),
                    "sub_fields": sub_fields,
                    "required": field.required,
                    "to_many_relation": to_many_relation
                })
            # FIXME:
            # Show more attibutes of `field`?

        return fields 
开发者ID:manosim,项目名称:django-rest-framework-docs,代码行数:26,代码来源:api_endpoint.py

示例2: __init__

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import BaseSerializer [as 别名]
def __init__(self, *args, **kwargs):
        """
        Gets the kwargs passed to the serializer and produces a new data dictionary with:
            address: string
            creation_date_time: datetime
            creation_block: int

        In addition, all parameters contained in kwargs['data']['params'] are re-elaborated and added to
        the final data dictionary
        """
        # Remove those args not compliant with `serializers.BaseSerializer`
        block = kwargs.pop('block', None) # Avoid KeyError in case key is not in dictionary

        if block:
            self.block = block

        super().__init__(*args, **kwargs)

        self.initial_data = self.parse_event_data(kwargs.pop('data')) 
开发者ID:gnosis,项目名称:pm-trading-db,代码行数:21,代码来源:serializers.py

示例3: extract_attributes

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import BaseSerializer [as 别名]
def extract_attributes(cls, fields, resource):
        """
        Builds the `attributes` object of the JSON API resource object.
        """
        data = OrderedDict()
        render_nested_as_attribute = json_api_settings.SERIALIZE_NESTED_SERIALIZERS_AS_ATTRIBUTE
        for field_name, field in iter(fields.items()):
            # ID is always provided in the root of JSON API so remove it from attributes
            if field_name == 'id':
                continue
            # don't output a key for write only fields
            if fields[field_name].write_only:
                continue
            # Skip fields with relations
            if isinstance(
                    field, (relations.RelatedField, relations.ManyRelatedField)
            ):
                continue

            if isinstance(field, BaseSerializer) and not render_nested_as_attribute:
                continue

            # Skip read_only attribute fields when `resource` is an empty
            # serializer. Prevents the "Raw Data" form of the browsable API
            # from rendering `"foo": null` for read only fields
            try:
                resource[field_name]
            except KeyError:
                if fields[field_name].read_only:
                    continue

            data.update({
                field_name: resource.get(field_name)
            })

        return utils.format_field_names(data) 
开发者ID:django-json-api,项目名称:django-rest-framework-json-api,代码行数:38,代码来源:renderers.py

示例4: _get_field_type

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import BaseSerializer [as 别名]
def _get_field_type(serializer, field_name, field, include_read_only):
    """
    Try to describe a field type.
    """
    if not include_read_only and hasattr(field, 'writable_doc_format'):
        return _get_type_from_docstring(field.writable_doc_format)

    if hasattr(field, 'doc_format'):
        return _get_type_from_docstring(field.doc_format)

    if isinstance(field, (relations.ManyRelatedField, serializers.ListSerializer)):
        # Many field, recurse on child and make it a list
        if isinstance(field, relations.ManyRelatedField):
            field = field.child_relation
        else:
            field = field.child
        return [_get_field_type(serializer, field_name, field, include_read_only)]

    if field.__class__.__name__ in _SERIALIZER_DEFS:
        return _SERIALIZER_DEFS[field.__class__.__name__]

    if isinstance(field, serializers.SlugRelatedField):
        return _get_details_for_slug(serializer, field_name, field)

    if isinstance(field, serializers.SerializerMethodField):
        # For method fields try to use docstring of the method.
        method_name = field.method_name or 'get_{field_name}'.format(field_name=field_name)
        method = getattr(serializer, method_name, None)
        if method:
            docstring = getattr(method, '__doc__')
            return _get_type_from_docstring(docstring, docstring or 'method')

    if isinstance(field, serializers.BaseSerializer):
        return describe_serializer(field, include_read_only)

    logger = logging.getLogger(__name__)
    logger.error('Undocumented field %s' % field)
    return 'UNKNOWN' 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:40,代码来源:renderers_serializers.py

示例5: proxied

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import BaseSerializer [as 别名]
def proxied(self):
        if not self._proxied:
            if self.bind_args:
                field_name, parent = self.bind_args

                if hasattr(parent, 'child') and parent.child is self:
                    # RecursiveField nested inside of a ListField
                    parent_class = parent.parent.__class__
                else:
                    # RecursiveField directly inside a Serializer
                    parent_class = parent.__class__

                assert issubclass(parent_class, BaseSerializer)

                if self.to is None:
                    proxied_class = parent_class
                else:
                    try:
                        module_name, class_name = self.to.rsplit('.', 1)
                    except ValueError:
                        module_name, class_name = parent_class.__module__, self.to

                    try:
                        proxied_class = getattr(
                            importlib.import_module(module_name), class_name)
                    except Exception as e:
                        raise ImportError(
                            'could not locate serializer %s' % self.to, e)

                # Create a new serializer instance and proxy it
                proxied = proxied_class(**self.init_kwargs)
                proxied.bind(field_name, parent)
                self._proxied = proxied
                
        return self._proxied 
开发者ID:heywbj,项目名称:django-rest-framework-recursive,代码行数:37,代码来源:fields.py

示例6: raise_errors_on_nested_writes

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import BaseSerializer [as 别名]
def raise_errors_on_nested_writes(method_name, serializer, validated_data):
    # *** inherited from DRF 3, altered for EmbeddedDocumentSerializer to pass ***
    assert not any(
        isinstance(field, serializers.BaseSerializer) and
        not isinstance(field, EmbeddedDocumentSerializer) and
        (key in validated_data)
        for key, field in serializer.fields.items()
    ), (
        'The `.{method_name}()` method does not support writable nested'
        'fields by default.\nWrite an explicit `.{method_name}()` method for '
        'serializer `{module}.{class_name}`, or set `read_only=True` on '
        'nested serializer fields.'.format(
            method_name=method_name,
            module=serializer.__class__.__module__,
            class_name=serializer.__class__.__name__
        )
    )

    assert not any(
        '.' in field.source and (key in validated_data) and
        isinstance(validated_data[key], (list, dict))
        for key, field in serializer.fields.items()
    ), (
        'The `.{method_name}()` method does not support writable dotted-source '
        'fields by default.\nWrite an explicit `.{method_name}()` method for '
        'serializer `{module}.{class_name}`, or set `read_only=True` on '
        'dotted-source serializer fields.'.format(
            method_name=method_name,
            module=serializer.__class__.__module__,
            class_name=serializer.__class__.__name__
        )
    ) 
开发者ID:umutbozkurt,项目名称:django-rest-framework-mongoengine,代码行数:34,代码来源:serializers.py

示例7: _get_field_object

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import BaseSerializer [as 别名]
def _get_field_object(self, request=False):
        """
        Creates swagger object for field for request or response

        :param request: is this object for request?
        :return: swagger object
        :rtype: OrderedDict
        """
        if isinstance(self._field, BaseSerializer):
            if getattr(self._field, 'many', None):
                result = {
                    'type': 'array',
                    'items': self._serializer_inrospector_class(self._field).build_response_object(),
                }
            else:
                result = self._serializer_inrospector_class(self._field).build_response_object()
        else:
            field_type, data_type, data_format = self._get_field_type(self._field)
            if data_type == 'file' and not request:
                data_type = 'string'
            result = OrderedDict(type=data_type)

            # Retrieve Field metadata
            max_val = getattr(self._field, 'max_value', None)
            min_val = getattr(self._field, 'min_value', None)
            max_length = getattr(self._field, 'max_length', None)
            default = self._get_default_value()
            description = getattr(self._field, 'help_text', '')

            if data_format:
                result['format'] = data_format

            if max_val is not None and data_type in ('integer', 'number'):
                result['minimum'] = min_val

            if max_val is not None and data_type in ('integer', 'number'):
                result['maximum'] = max_val

            if max_length is not None and data_type == 'string':
                result['maxLength'] = max_length

            if description:
                result['description'] = description

            if default is not None:
                result['default'] = default

            if field_type in ['multiple choice', 'choice']:
                if isinstance(self._field.choices, dict):
                    result['enum'] = [k for k in self._field.choices]

                if all(isinstance(item, int) for item in result.get('enum', ['1'])):
                    result['type'] = 'integer'
        return result 
开发者ID:Arello-Mobile,项目名称:py2swagger,代码行数:56,代码来源:field.py


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