def metadata(self):
     """
     Return a dictionary of metadata about the fields on the serializer.
     Useful for things like responding to OPTIONS requests, or generating
     API schemas for auto-documentation.
     """
     return SortedDict([(field_name, field.metadata()) for field_name, field in six.iteritems(self.fields)])
示例#2
0
    def render(self, data, *args, **kwargs):
        charset = 'utf-8'
        root_node = 'xforms'
        xmlns = "http://openrosa.org/xforms/xformsList"

        if 'detail' in data.keys():
            stream = StringIO()

            xml = SimplerXMLGenerator(stream, charset)
            xml.startDocument()
            xml.startElement(root_node, {'xmlns': xmlns})

            for key, value in six.iteritems(data):
                xml.startElement(key, {})
                xml.characters(smart_text(value))
                xml.endElement(key)

            xml.endElement(root_node)
            xml.endDocument()
            return stream.getvalue()
        else:
            json = self.transform_to_xform_json(data)
            survey = create_survey_element_from_dict(json)
            xml = survey.xml()
            fix_languages(xml)
            xml = xml.toxml()

            xml = self.insert_version_attribute(xml,
                                                data.get('id_string'),
                                                data.get('version'))
            xml = self.insert_uuid_bind(xml, data.get('id_string'))

            return xml
示例#3
0
    def render(self, data, *args, **kwargs):
        charset = 'utf-8'
        root_node = 'xforms'
        xmlns = "http://openrosa.org/xforms/xformsList"

        if 'detail' in data.keys():
            stream = StringIO()

            xml = SimplerXMLGenerator(stream, charset)
            xml.startDocument()
            xml.startElement(root_node, {'xmlns': xmlns})

            for key, value in six.iteritems(data):
                xml.startElement(key, {})
                xml.characters(smart_text(value))
                xml.endElement(key)

            xml.endElement(root_node)
            xml.endDocument()
            return stream.getvalue()
        else:
            json = self.transform_to_xform_json(data)
            survey = create_survey_element_from_dict(json)
            xml = survey.xml()
            fix_languages(xml)
            xml = xml.toxml()

            xml = self.insert_version_attribute(xml,
                                                data.get('id_string'),
                                                data.get('version'))
            xml = self.insert_uuid_bind(xml, data.get('id_string'))

            return xml
示例#4
0
 def _filter_dict(self, value):
     if isinstance(value, dict):
         return dict(
             (k, v)
             for k, v in six.iteritems(value)
             if k in self.included_keys
         )
     return value
 def metadata(self):
     """
     Return a dictionary of metadata about the fields on the serializer.
     Useful for things like responding to OPTIONS requests, or generating
     API schemas for auto-documentation.
     """
     return SortedDict([(field_name, field.metadata())
                        for field_name, field in six.iteritems(self.fields)
                        ])
 def __init__(self, serializers, *args, **kwargs):
     """
     Needs an extra parameter `serializers` which has to be a dict
     key: value being `Model`: serializer.
     """
     super(GenericRelatedField, self).__init__(*args, **kwargs)
     self.serializers = serializers
     for model, serializer in six.iteritems(self.serializers):
         # We have to do it, because the serializer can't access a
         # explicit manager through the GenericForeignKey field on
         # the model.
         if hasattr(serializer, 'queryset') and serializer.queryset is None:
             serializer.queryset = model._default_manager.all()
示例#7
0
    def run_validators(self, value):
        super(DictField, self).run_validators(value)

        if self.value_field:
            errors = {}
            for k, v in six.iteritems(value):
                try:
                    self.value_field.run_validators(v)
                except ValidationError as e:
                    errors[k] = e.messages

            if errors:
                raise NestedValidationError(errors)
示例#8
0
    def _to_xml(self, xml, data):
        if isinstance(data, (list, tuple)):
            for item in data:
                xml.startElement(self.element_node, {})
                self._to_xml(xml, item)
                xml.endElement(self.element_node)

        elif isinstance(data, dict):
            for key, value in six.iteritems(data):
                xml.startElement(key, {})
                self._to_xml(xml, value)
                xml.endElement(key)

        else:
            xml.characters(smart_text(data))
示例#9
0
    def __init__(self, data=None, status=200, template_name=None, headers=None, exception=False, content_type=None):
        """
        Alters the init arguments slightly.
        For example, drop 'template_name', and instead use 'data'.

        Setting 'renderer' and 'media_type' will typically be deferred,
        For example being set automatically by the `APIView`.
        """
        super(Response, self).__init__(None, status=status)
        self.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
示例#10
0
    def _to_xml(self, xml, data):
        if isinstance(data, (list, tuple)):
            for item in data:
                xml.startElement("list-item", {})
                self._to_xml(xml, item)
                xml.endElement("list-item")

        elif isinstance(data, dict):
            for key, value in six.iteritems(data):
                xml.startElement(key, {})
                self._to_xml(xml, value)
                xml.endElement(key)

        elif data is None:
            # Don't output any value
            pass

        else:
            xml.characters(smart_text(data))
    def _to_xml(self, xml, data):
        if isinstance(data, (list, tuple)):
            for item in data:
                xml.startElement("list-item", {})
                self._to_xml(xml, item)
                xml.endElement("list-item")

        elif isinstance(data, dict):
            for key, value in six.iteritems(data):
                xml.startElement(key, {})
                self._to_xml(xml, value)
                xml.endElement(key)

        elif data is None:
            # Don't output any value
            pass

        else:
            xml.characters(smart_text(data))
示例#12
0
    def __init__(self, data=None, status=200,
                 template_name=None, headers=None,
                 exception=False, content_type=None):
        """
        Alters the init arguments slightly.
        For example, drop 'template_name', and instead use 'data'.

        Setting 'renderer' and 'media_type' will typically be deferred,
        For example being set automatically by the `APIView`.
        """
        super(Response, self).__init__(None, status=status)
        self.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
    def __init__(self, serializers, determining_errors=None, *args, **kwargs):
        """
        Needs an extra parameter `serializers` which has to be a dict
        key: value being `Model`: serializer.

        Supports a `determining_errors` parameter which is a list of
        ValidationError messages which should, in
        determine_serializer_for_data(), indicate that the respective
        serializer is not a match for the value. Default `None` means that any
        ValidationError indicates a mismatch.
        """
        super(GenericRelatedField, self).__init__(*args, **kwargs)
        self.serializers = serializers
        self.determining_errors = determining_errors
        for model, serializer in six.iteritems(self.serializers):
            # We have to do it, because the serializer can't access a
            # explicit manager through the GenericForeignKey field on
            # the model.
            if hasattr(serializer, 'queryset') and serializer.queryset is None:
                serializer.queryset = model._default_manager.all()
    def __init__(self, serializers, determining_errors=None, *args, **kwargs):
        """
        Needs an extra parameter `serializers` which has to be a dict
        key: value being `Model`: serializer.

        Supports a `determining_errors` parameter which is a list of
        ValidationError messages which should, in
        determine_serializer_for_data(), indicate that the respective
        serializer is not a match for the value. Default `None` means that any
        ValidationError indicates a mismatch.
        """
        super(GenericRelatedField, self).__init__(*args, **kwargs)
        self.serializers = serializers
        self.determining_errors = determining_errors
        for model, serializer in six.iteritems(self.serializers):
            # We have to do it, because the serializer can't access a
            # explicit manager through the GenericForeignKey field on
            # the model.
            if hasattr(serializer, 'queryset') and serializer.queryset is None:
                serializer.queryset = model._default_manager.all()
示例#15
0
def _get_declared_fields(bases, attrs):
    """
    Create a list of serializer field instances from the passed in 'attrs',
    plus any fields on the base classes (in 'bases').

    Note that all fields from the base classes are used.
    """
    fields = [(field_name, attrs.pop(field_name))
              for field_name, obj in list(six.iteritems(attrs))
              if isinstance(obj, Field)]
    fields.sort(key=lambda x: x[1].creation_counter)

    # If this class is subclassing another Serializer, add that Serializer's
    # fields.  Note that we loop over the bases in *reverse*. This is necessary
    # in order to maintain the correct order of fields.
    for base in bases[::-1]:
        if hasattr(base, 'base_fields'):
            fields = list(base.base_fields.items()) + fields

    return SortedDict(fields)
示例#16
0
def _get_declared_fields(bases, attrs):
    """
    Create a list of serializer field instances from the passed in 'attrs',
    plus any fields on the base classes (in 'bases').

    Note that all fields from the base classes are used.
    """
    fields = [(field_name, attrs.pop(field_name))
              for field_name, obj in list(six.iteritems(attrs))
              if isinstance(obj, Field)]
    fields.sort(key=lambda x: x[1].creation_counter)

    # If this class is subclassing another Serializer, add that Serializer's
    # fields.  Note that we loop over the bases in *reverse*. This is necessary
    # in order to maintain the correct order of fields.
    for base in bases[::-1]:
        if hasattr(base, 'base_fields'):
            fields = list(base.base_fields.items()) + fields

    return SortedDict(fields)
示例#17
0
    def _to_xml(self, xml, data):
        if isinstance(data, (list, tuple, types.GeneratorType, islice)):
            for item in data:
                xml.startElement("list-item", {})
                self._to_xml(xml, item)
                xml.endElement("list-item")

        elif isinstance(data, dict):
            for key, value in six.iteritems(data):
                xml.startElement(key, {})
                self._to_xml(xml, value)
                xml.endElement(key)

        elif isinstance(data, (geometry.LineString, geometry.MultiLineString, geometry.MultiPoint, geometry.MultiPolygon, geometry.Point, geometry.Polygon)):
            return self._to_xml(xml, data.__geo_interface__)

        elif data is None:
            # Don't output any value
            pass

        else:
            xml.characters(smart_text(data))
示例#18
0
    def _to_xml(self, xml, data):
        if isinstance(data, (list, tuple, types.GeneratorType, islice)):
            for item in data:
                xml.startElement("list-item", {})
                self._to_xml(xml, item)
                xml.endElement("list-item")

        elif isinstance(data, dict):
            for key, value in six.iteritems(data):
                xml.startElement(key, {})
                self._to_xml(xml, value)
                xml.endElement(key)

        elif isinstance(data, (geometry.LineString, geometry.MultiLineString, geometry.MultiPoint, geometry.MultiPolygon, geometry.Point, geometry.Polygon)):
            return self._to_xml(xml, data.__geo_interface__)

        elif data is None:
            # Don't output any value
            pass

        else:
            xml.characters(smart_text(data))