コード例 #1
0
ファイル: _inbase.py プロジェクト: dgambacorta/showroomstock
    def __init__(self,
                 app=None,
                 validator=None,
                 mime_type=None,
                 ignore_wrappers=False,
                 binary_encoding=None):

        self.validator = None

        super(InProtocolBase, self).__init__(app=app,
                                             mime_type=mime_type,
                                             ignore_wrappers=ignore_wrappers,
                                             binary_encoding=binary_encoding)

        self.message = None
        self.validator = None
        self.set_validator(validator)

        if self.binary_encoding is None:
            self.binary_encoding = self.default_binary_encoding

        if mime_type is not None:
            self.mime_type = mime_type

        fsh = {
            Null: self.null_from_string,
            Time: self.time_from_string,
            Date: self.date_from_string,
            Uuid: self.uuid_from_string,
            File: self.file_from_string,
            Array: self.array_from_string,
            Double: self.double_from_string,
            String: self.string_from_string,
            AnyXml: self.any_xml_from_string,
            Boolean: self.boolean_from_string,
            Integer: self.integer_from_string,
            Unicode: self.unicode_from_string,
            Decimal: self.decimal_from_string,
            AnyHtml: self.any_html_from_string,
            DateTime: self.datetime_from_string,
            Duration: self.duration_from_string,
            ByteArray: self.byte_array_from_string,
            EnumBase: self.enum_base_from_string,
            ModelBase: self.model_base_from_string,
            Attachment: self.attachment_from_string,
            XmlAttribute: self.xmlattribute_from_string,
            ComplexModelBase: self.complex_model_base_from_string
        }

        self._from_string_handlers = cdict(fsh)
        self._from_unicode_handlers = cdict(fsh)

        self._datetime_dsmap = {
            None: self._datetime_from_string,
            'sec': self._datetime_from_sec,
            'sec_float': self._datetime_from_sec_float,
            'msec': self._datetime_from_msec,
            'msec_float': self._datetime_from_msec_float,
            'usec': self._datetime_from_usec,
        }
コード例 #2
0
ファイル: _base.py プロジェクト: shaung/spyne
    def __init__(self, app=None, validator=None, xml_declaration=True,
                                                    cleanup_namespaces=False):
        ProtocolBase.__init__(self, app, validator)
        self.xml_declaration = xml_declaration
        self.cleanup_namespaces = cleanup_namespaces

        self.serialization_handlers = cdict({
            AnyXml: xml_to_parent_element,
            Alias: alias_to_parent_element,
            Fault: fault_to_parent_element,
            AnyDict: dict_to_parent_element,
            EnumBase: enum_to_parent_element,
            ModelBase: base_to_parent_element,
            ByteArray: binary_to_parent_element,
            Attachment: binary_to_parent_element,
            ComplexModelBase: complex_to_parent_element,
        })

        self.deserialization_handlers = cdict({
            AnyXml: xml_from_element,
            Fault: fault_from_element,
            AnyDict: dict_from_element,
            EnumBase: enum_from_element,
            ModelBase: base_from_element,
            Unicode: unicode_from_element,
            ByteArray: binary_from_element,
            Attachment: binary_from_element,
            ComplexModelBase: complex_from_element,

            Iterable: iterable_from_element,
            Array: array_from_element,
        })

        self.log_messages = (logger.level == logging.DEBUG)
コード例 #3
0
ファイル: _base.py プロジェクト: esauro/spyne
    def __init__(self, app=None, validator=None, mime_type=None,
                                                            ignore_uncap=False):
        self.__app = None
        self.validator = None

        self.set_app(app)
        self.event_manager = EventManager(self)
        self.set_validator(validator)
        self.ignore_uncap = ignore_uncap
        if mime_type is not None:
            self.mime_type = mime_type

        self._to_string_handlers = cdict({
            ModelBase: lambda cls, value: cls.to_string(value),
            Time: time_to_string,
            Uuid: uuid_to_string,
            Null: null_to_string,
            Double: double_to_string,
            AnyXml: any_xml_to_string,
            Unicode: unicode_to_string,
            Boolean: boolean_to_string,
            Decimal: decimal_to_string,
            Integer: integer_to_string,
            AnyHtml: any_html_to_string,
            DateTime: datetime_to_string,
            Duration: duration_to_string,
            ByteArray: byte_array_to_string,
            Attachment: attachment_to_string,
            ComplexModelBase: complex_model_base_to_string,
        })

        self._to_string_iterable_handlers = cdict({
            File: file_to_string_iterable,
            ByteArray: byte_array_to_string_iterable,
            ModelBase: lambda prot, cls, value: cls.to_string_iterable(value),
            SimpleModel: simple_model_to_string_iterable,
            ComplexModelBase: complex_model_to_string_iterable,
        })

        self._from_string_handlers = cdict({
            Null: null_from_string,
            Time: time_from_string,
            Date: date_from_string,
            Uuid: uuid_from_string,
            File: file_from_string,
            Double: double_from_string,
            String: string_from_string,
            AnyXml: any_xml_from_string,
            Boolean: boolean_from_string,
            Integer: integer_from_string,
            Unicode: unicode_from_string,
            Decimal: decimal_from_string,
            AnyHtml: any_html_from_string,
            DateTime: datetime_from_string,
            Duration: duration_from_string,
            ByteArray: byte_array_from_string,
            Attachment: attachment_from_string,
            ComplexModelBase: complex_model_base_from_string
        })
コード例 #4
0
    def __init__(self, app=None, validator=None, mime_type=None,
                                                            ignore_uncap=False):
        self.__app = None
        self.validator = None

        self.set_app(app)
        self.event_manager = EventManager(self)
        self.set_validator(validator)
        self.ignore_uncap = ignore_uncap
        if mime_type is not None:
            self.mime_type = mime_type

        self._to_string_handlers = cdict({
            ModelBase: lambda cls, value: cls.to_string(value),
            Time: time_to_string,
            Uuid: uuid_to_string,
            Null: null_to_string,
            Double: double_to_string,
            AnyXml: any_xml_to_string,
            Unicode: unicode_to_string,
            Boolean: boolean_to_string,
            Decimal: decimal_to_string,
            Integer: integer_to_string,
            AnyHtml: any_html_to_string,
            DateTime: datetime_to_string,
            Duration: duration_to_string,
            ByteArray: byte_array_to_string,
            Attachment: attachment_to_string,
            ComplexModelBase: complex_model_base_to_string,
        })

        self._to_string_iterable_handlers = cdict({
            File: file_to_string_iterable,
            ByteArray: byte_array_to_string_iterable,
            ModelBase: lambda prot, cls, value: cls.to_string_iterable(value),
            SimpleModel: simple_model_to_string_iterable,
        })

        self._from_string_handlers = cdict({
            Null: null_from_string,
            Time: time_from_string,
            Date: date_from_string,
            Uuid: uuid_from_string,
            File: file_from_string,
            Double: double_from_string,
            String: string_from_string,
            AnyXml: any_xml_from_string,
            Boolean: boolean_from_string,
            Integer: integer_from_string,
            Unicode: unicode_from_string,
            Decimal: decimal_from_string,
            AnyHtml: any_html_from_string,
            DateTime: datetime_from_string,
            Duration: duration_from_string,
            ByteArray: byte_array_from_string,
            Attachment: attachment_from_string,
            ComplexModelBase: complex_model_base_from_string
        })
コード例 #5
0
ファイル: _base.py プロジェクト: fmezas/spyne
    def __init__(self,
                 app=None,
                 validator=None,
                 xml_declaration=True,
                 cleanup_namespaces=True,
                 encoding='UTF-8',
                 pretty_print=False):
        ProtocolBase.__init__(self, app, validator)
        self.xml_declaration = xml_declaration
        self.cleanup_namespaces = cleanup_namespaces
        self.encoding = encoding
        self.pretty_print = pretty_print

        self.serialization_handlers = cdict({
            AnyXml:
            xml_to_parent_element,
            Alias:
            alias_to_parent_element,
            Fault:
            fault_to_parent_element,
            AnyDict:
            dict_to_parent_element,
            AnyHtml:
            html_to_parent_element,
            EnumBase:
            enum_to_parent_element,
            ModelBase:
            base_to_parent_element,
            ByteArray:
            byte_array_to_parent_element,
            Attachment:
            attachment_to_parent_element,
            XmlAttribute:
            xmlattribute_to_parent_element,
            ComplexModelBase:
            complex_to_parent_element,
        })

        self.deserialization_handlers = cdict({
            AnyXml: xml_from_element,
            Fault: fault_from_element,
            AnyDict: dict_from_element,
            EnumBase: enum_from_element,
            ModelBase: base_from_element,
            Unicode: unicode_from_element,
            ByteArray: byte_array_from_element,
            Attachment: attachment_from_element,
            ComplexModelBase: complex_from_element,
            Alias: alias_from_element,
            Iterable: iterable_from_element,
            Array: array_from_element,
        })

        self.log_messages = (logger.level == logging.DEBUG)
        self.parser = etree.XMLParser(remove_comments=True)
コード例 #6
0
ファイル: _inbase.py プロジェクト: hozn/spyne
    def __init__(self, app=None, validator=None, mime_type=None,
                                   ignore_wrappers=False, binary_encoding=None):

        self.validator = None

        super(InProtocolBase, self).__init__(app=app, mime_type=mime_type,
               ignore_wrappers=ignore_wrappers, binary_encoding=binary_encoding)

        self.message = None
        self.validator = None
        self.set_validator(validator)

        if self.binary_encoding is None:
            self.binary_encoding = self.default_binary_encoding

        if mime_type is not None:
            self.mime_type = mime_type

        fsh = {
            Null: self.null_from_string,
            Time: self.time_from_string,
            Date: self.date_from_string,
            Uuid: self.uuid_from_string,
            File: self.file_from_string,
            Array: self.array_from_string,
            Double: self.double_from_string,
            String: self.string_from_string,
            AnyXml: self.any_xml_from_string,
            Boolean: self.boolean_from_string,
            Integer: self.integer_from_string,
            Unicode: self.unicode_from_string,
            Decimal: self.decimal_from_string,
            AnyHtml: self.any_html_from_string,
            DateTime: self.datetime_from_string,
            Duration: self.duration_from_string,
            ByteArray: self.byte_array_from_string,
            EnumBase: self.enum_base_from_string,
            ModelBase: self.model_base_from_string,
            Attachment: self.attachment_from_string,
            XmlAttribute: self.xmlattribute_from_string,
            ComplexModelBase: self.complex_model_base_from_string
        }

        self._from_string_handlers = cdict(fsh)
        self._from_unicode_handlers = cdict(fsh)

        self._datetime_dsmap = {
            None: self._datetime_from_string,
            'sec': self._datetime_from_sec,
            'sec_float': self._datetime_from_sec_float,
            'msec': self._datetime_from_msec,
            'msec_float': self._datetime_from_msec_float,
            'usec': self._datetime_from_usec,
        }
コード例 #7
0
ファイル: _base.py プロジェクト: norox/spyne
    def __new__(cls, cls_name, cls_bases, cls_dict):
        for dkey in ("_to_string_handlers", "_to_string_iterable_handlers",
                                 "_from_string_handlers", '_to_dict_handlers'):
            d = cdict()
            for b in cls_bases:
                d_base = getattr(b, dkey, cdict())
                d.update(d_base) 

            d.update(cdict(cls_dict.get(dkey, {})))
            cls_dict[dkey] = d

        return type(object).__new__(cls, cls_name, cls_bases, cls_dict)
コード例 #8
0
    def __new__(cls, cls_name, cls_bases, cls_dict):
        for dkey in ("_to_string_handlers", "_to_string_iterable_handlers",
                     "_from_string_handlers", '_to_dict_handlers'):
            d = cdict()
            for b in cls_bases:
                d_base = getattr(b, dkey, cdict())
                d.update(d_base)

            d.update(cdict(cls_dict.get(dkey, {})))
            cls_dict[dkey] = d

        return type(object).__new__(cls, cls_name, cls_bases, cls_dict)
コード例 #9
0
ファイル: _base.py プロジェクト: specialunderwear/spyne
    def __init__(
        self,
        app=None,
        validator=None,
        xml_declaration=True,
        cleanup_namespaces=True,
        encoding="UTF-8",
        pretty_print=False,
    ):
        ProtocolBase.__init__(self, app, validator)
        self.xml_declaration = xml_declaration
        self.cleanup_namespaces = cleanup_namespaces
        self.encoding = encoding
        self.pretty_print = pretty_print

        self.serialization_handlers = cdict(
            {
                AnyXml: xml_to_parent_element,
                Alias: alias_to_parent_element,
                Fault: fault_to_parent_element,
                AnyDict: dict_to_parent_element,
                AnyHtml: html_to_parent_element,
                EnumBase: enum_to_parent_element,
                ModelBase: base_to_parent_element,
                ByteArray: byte_array_to_parent_element,
                Attachment: attachment_to_parent_element,
                ComplexModelBase: complex_to_parent_element,
            }
        )

        self.deserialization_handlers = cdict(
            {
                AnyXml: xml_from_element,
                Fault: fault_from_element,
                AnyDict: dict_from_element,
                EnumBase: enum_from_element,
                ModelBase: base_from_element,
                Unicode: unicode_from_element,
                ByteArray: byte_array_from_element,
                Attachment: attachment_from_element,
                ComplexModelBase: complex_from_element,
                Alias: alias_from_element,
                Iterable: iterable_from_element,
                Array: array_from_element,
            }
        )

        self.log_messages = logger.level == logging.DEBUG
        self.parser = etree.XMLParser(remove_comments=True)
コード例 #10
0
    def test_cdict(self):
        from spyne.util.cdict import cdict

        class A(object):
            pass

        class B(A):
            pass

        class E(B):
            pass

        class F(E):
            pass

        class C(object):
            pass

        class D:
            pass

        d = cdict({A: "fun", object: "base", F: 'zan'})

        assert d[A] == 'fun'
        assert d[B] == 'fun'
        assert d[C] == 'base'
        assert d[F] == 'zan'
        try:
            d[D]
        except KeyError:
            pass
        else:
            raise Exception("Must fail.")
コード例 #11
0
ファイル: to_parent.py プロジェクト: jstuyck/spyne
    def __init__(self, app=None, validator=None, mime_type=None,
                 ignore_uncap=False, ignore_wrappers=False, polymorphic=True):
        super(ToParentMixin, self).__init__(app=app, validator=validator,
                                 mime_type=mime_type, ignore_uncap=ignore_uncap,
                                 ignore_wrappers=ignore_wrappers)

        self.polymorphic = polymorphic
        self.use_global_null_handler = True

        self.serialization_handlers = cdict({
            ModelBase: self.base_to_parent,

            AnyXml: self.xml_to_parent,
            AnyUri: self.anyuri_to_parent,
            ImageUri: self.imageuri_to_parent,
            AnyDict: self.dict_to_parent,
            AnyHtml: self.html_to_parent,
            Any: self.any_to_parent,

            Fault: self.fault_to_parent,
            EnumBase: self.enum_to_parent,
            ByteArray: self.byte_array_to_parent,
            ComplexModelBase: self.complex_to_parent,
            SchemaValidationError: self.schema_validation_error_to_parent,
        })
コード例 #12
0
ファイル: widget.py プロジェクト: cemrecan/neurons
    def __init__(self, text_field=None, id_field=None, type=None,
                             hidden_fields=None, label=True, null_str='[NULL]'):
        """A widget that renders complex objects as links.

        :param text_field: The name of the field containing a human readable
            string that represents the object.
        :param id_field: The name of the field containing the unique identifier
            of the object.
        :param type: If not `None`, overrides the object type being rendered.
            Useful for e.g. combining multiple fields to one field.
        :param hidden_fields: A sequence of field names that will be rendered as
            hidden <input> tags.
        :param label: If ``True``, a ``<label>`` tag is generated for the
            relevant widget id.
        """

        super(ComplexRenderWidget, self).__init__(label=label)

        self.id_field = id_field
        self.text_field = text_field
        self.hidden_fields = hidden_fields
        self.type = type
        self.null_str = null_str

        self.serialization_handlers = cdict({
            ComplexModelBase: self.complex_model_to_parent,
        })
コード例 #13
0
ファイル: test_util.py プロジェクト: sashka/spyne
    def test_cdict(self):
        from spyne.util.cdict import cdict

        class A(object):
            pass

        class B(A):
            pass

        class E(B):
            pass

        class F(E):
            pass

        class C(object):
            pass

        class D:
            pass

        d = cdict({A: "fun", object: "base", F: 'zan'})

        assert d[A] == 'fun'
        assert d[B] == 'fun'
        assert d[C] == 'base'
        assert d[F] == 'zan'
        try:
            d[D]
        except KeyError:
            pass
        else:
            raise Exception("Must fail.")
コード例 #14
0
ファイル: widget.py プロジェクト: cemrecan/neurons
    def __init__(self, *args, **kwargs):
        super(PasswordWidget, self).__init__(*args, **kwargs)

        self.serialization_handlers = cdict({
            Unicode: self.unicode_to_parent,
            ComplexModelBase: self.complex_model_to_parent,
        })
コード例 #15
0
ファイル: to_parent.py プロジェクト: tunks/spyne
    def __init__(self,
                 app=None,
                 validator=None,
                 mime_type=None,
                 ignore_uncap=False,
                 ignore_wrappers=False):
        super(ToParentMixin, self).__init__(app=app,
                                            validator=validator,
                                            mime_type=mime_type,
                                            ignore_uncap=ignore_uncap,
                                            ignore_wrappers=ignore_wrappers)

        self.serialization_handlers = cdict({
            AnyXml:
            self.xml_to_parent,
            Fault:
            self.fault_to_parent,
            AnyDict:
            self.dict_to_parent,
            AnyHtml:
            self.html_to_parent,
            EnumBase:
            self.enum_to_parent,
            ModelBase:
            self.base_to_parent,
            ByteArray:
            self.byte_array_to_parent,
            ComplexModelBase:
            self.complex_to_parent,
            SchemaValidationError:
            self.schema_validation_error_to_parent,
        })
コード例 #16
0
ファイル: form.py プロジェクト: payingattention/neurons
    def __init__(self, app=None, ignore_uncap=False, ignore_wrappers=False,
                       cloth=None, attr_name='spyne_id', root_attr_name='spyne',
                            cloth_parser=None, polymorphic=True, hier_delim='.',
                                                                asset_paths={}):

        super(HtmlForm, self).__init__(app=app,
                     ignore_uncap=ignore_uncap, ignore_wrappers=ignore_wrappers,
                cloth=cloth, attr_name=attr_name, root_attr_name=root_attr_name,
                             cloth_parser=cloth_parser, polymorphic=polymorphic)

        self.serialization_handlers = cdict({
            Date: self.date_to_parent,
            Time: self.time_to_parent,
            Array: self.array_type_to_parent,
            Integer: self.integer_to_parent,
            Unicode: self.unicode_to_parent,
            Decimal: self.decimal_to_parent,
            Boolean: self.boolean_to_parent,
            Duration: self.duration_to_parent,
            DateTime: self.datetime_to_parent,
            ComplexModelBase: self.complex_model_to_parent,
        })

        self.hier_delim = hier_delim

        self.asset_paths = {
            ('jquery',): [_jstag("/assets/jquery/1.11.1/jquery.min.js")],
            ('jquery-ui',): [_jstag("/assets/jquery-ui/1.11.0/jquery-ui.min.js")],
            ('jquery-timepicker',): [
                _jstag("/assets/jquery-timepicker/jquery-ui-timepicker-addon.js"),
                _csstag("/assets/jquery-timepicker/jquery-ui-timepicker-addon.css"),
            ],
        }
        self.asset_paths.update(asset_paths)
        self.use_global_null_handler = False
コード例 #17
0
    def __init__(self,
                 app=None,
                 validator=None,
                 mime_type=None,
                 ignore_uncap=False,
                 ignore_wrappers=False,
                 polymorphic=True):
        super(ToClothMixin, self).__init__(app=app,
                                           validator=validator,
                                           mime_type=mime_type,
                                           ignore_uncap=ignore_uncap,
                                           ignore_wrappers=ignore_wrappers)

        self.polymorphic = polymorphic

        self.rendering_handlers = cdict({
            ModelBase:
            self.model_base_to_cloth,
            AnyXml:
            self.xml_to_cloth,
            AnyHtml:
            self.html_to_cloth,
            ComplexModelBase:
            self.complex_to_cloth,
        })
コード例 #18
0
ファイル: widget.py プロジェクト: arskom/neurons
    def __init__(self, label=True, type=None, hidden=False):
        super(SimpleReadableNumberWidget, self).__init__(
                                          label=label, type=type, hidden=hidden)

        self.serialization_handlers = cdict({
            Decimal: self.decimal_to_parent,
            Integer: self.integer_to_parent,
        })
コード例 #19
0
ファイル: widget.py プロジェクト: tayfundogan/neurons
    def __init__(self, label=True, type=None, hidden=False):
        super(SimpleRenderWidget, self).__init__(label=label)

        self.type = type
        self.hidden = hidden
        self.serialization_handlers = cdict({
            ModelBase: self.model_base_to_parent,
            ComplexModelBase: self.not_supported,
        })
コード例 #20
0
    def __init__(self, app=None, ignore_uncap=False, ignore_wrappers=False,
                                cloth=None, cloth_parser=None, polymorphic=True,
                                                      doctype="<!DOCTYPE html>",
                       root_tag='div', child_tag='div', field_name_attr='class',
                             field_name_tag=None, field_name_class='field_name',
                                                        before_first_root=None):
        """Protocol that returns the response object according to the "html
        microformat" specification. See
        https://en.wikipedia.org/wiki/Microformats for more info.

        The simple flavour is like the XmlDocument protocol, but returns data in
        <div> or <span> tags.

        :param app: A spyne.application.Application instance.
        :param root_tag: The type of the root tag that encapsulates the return
            data.
        :param child_tag: The type of the tag that encapsulates the fields of
            the returned object.
        :param field_name_attr: The name of the attribute that will contain the
            field names of the complex object children.
        """

        super(HtmlMicroFormat, self).__init__(app=app,
                     ignore_uncap=ignore_uncap, ignore_wrappers=ignore_wrappers,
                cloth=cloth, cloth_parser=cloth_parser, polymorphic=polymorphic,
                                               hier_delim=None, doctype=doctype)

        if six.PY2:
            text_type = basestring
        else:
            text_type = str

        assert isinstance(root_tag, text_type)
        assert isinstance(child_tag, text_type)
        assert isinstance(field_name_attr, text_type)
        assert field_name_tag is None or isinstance(field_name_tag, text_type)

        self.root_tag = root_tag
        self.child_tag = child_tag
        self.field_name_attr = field_name_attr
        self.field_name_tag = field_name_tag
        if field_name_tag is not None:
            self.field_name_tag = E(field_name_tag)
        self._field_name_class = field_name_class
        if before_first_root is not None:
            self.event_manager.add_listener("before_first_root",
                                                              before_first_root)

        self.serialization_handlers = cdict({
            Array: self.array_to_parent,
            AnyUri: self.anyuri_to_parent,
            AnyHtml: self.html_to_parent,
            ImageUri: self.imageuri_to_parent,
            ByteArray: self.not_supported,
            ModelBase: self.model_base_to_parent,
            ComplexModelBase: self.complex_model_to_parent,
        })
コード例 #21
0
ファイル: microformat.py プロジェクト: plq/spyne
    def __init__(self, app=None, ignore_uncap=False, ignore_wrappers=False,
                                cloth=None, cloth_parser=None, polymorphic=True,
                                                      doctype="<!DOCTYPE html>",
                       root_tag='div', child_tag='div', field_name_attr='class',
                             field_name_tag=None, field_name_class='field_name',
                                                        before_first_root=None):
        """Protocol that returns the response object according to the "html
        microformat" specification. See
        https://en.wikipedia.org/wiki/Microformats for more info.

        The simple flavour is like the XmlDocument protocol, but returns data in
        <div> or <span> tags.

        :param app: A spyne.application.Application instance.
        :param root_tag: The type of the root tag that encapsulates the return
            data.
        :param child_tag: The type of the tag that encapsulates the fields of
            the returned object.
        :param field_name_attr: The name of the attribute that will contain the
            field names of the complex object children.
        """

        super(HtmlMicroFormat, self).__init__(app=app,
                     ignore_uncap=ignore_uncap, ignore_wrappers=ignore_wrappers,
                cloth=cloth, cloth_parser=cloth_parser, polymorphic=polymorphic,
                                               hier_delim=None, doctype=doctype)

        if six.PY2:
            text_type = basestring
        else:
            text_type = str

        assert isinstance(root_tag, text_type)
        assert isinstance(child_tag, text_type)
        assert isinstance(field_name_attr, text_type)
        assert field_name_tag is None or isinstance(field_name_tag, text_type)

        self.root_tag = root_tag
        self.child_tag = child_tag
        self.field_name_attr = field_name_attr
        self.field_name_tag = field_name_tag
        if field_name_tag is not None:
            self.field_name_tag = E(field_name_tag)
        self._field_name_class = field_name_class
        if before_first_root is not None:
            self.event_manager.add_listener("before_first_root",
                                                              before_first_root)

        self.serialization_handlers = cdict({
            Array: self.array_to_parent,
            AnyUri: self.any_uri_to_parent,
            AnyHtml: self.any_html_to_parent,
            ImageUri: self.imageuri_to_parent,
            ByteArray: self.not_supported,
            ModelBase: self.model_base_to_parent,
            ComplexModelBase: self.complex_model_to_parent,
        })
コード例 #22
0
ファイル: widget.py プロジェクト: cemrecan/neurons
    def __init__(self, href, hidden_input=False, label=True):
        super(HrefWidget, self).__init__(label=label)

        self.href = href
        self.hidden_input = hidden_input

        self.serialization_handlers = cdict({
            ModelBase: self.model_base_to_parent,
            ComplexModelBase: self.not_supported,
        })
コード例 #23
0
ファイル: widget.py プロジェクト: yilmazalican/neurons
    def __init__(self, label=True, type=None, hidden=False):
        super(SimpleRenderWidget, self).__init__(label=label)

        self.type = type
        self.hidden = hidden
        self.serialization_handlers = cdict({
            ModelBase: self.model_base_to_parent,
            AnyHtml: self.any_html_to_parent,
            AnyUri: self.any_uri_to_parent,
            ComplexModelBase: self.complex_model_to_parent,
        })
コード例 #24
0
ファイル: table.py プロジェクト: mahdi-b/spyne
    def __init__(self, *args, **kwargs):
        super(HtmlRowTable, self).__init__(*args, **kwargs)

        self.serialization_handlers = cdict({
            ModelBase: self.model_base_to_parent,
            AnyUri: self.anyuri_to_parent,
            ImageUri: self.imageuri_to_parent,
            ByteArray: self.not_supported,
            ComplexModelBase: self.complex_model_to_parent,
            Array: self.array_to_parent,
        })
コード例 #25
0
    def __init__(self, *args, **kwargs):
        super(HtmlRowTable, self).__init__(*args, **kwargs)

        self.serialization_handlers = cdict({
            ModelBase: self.model_base_to_parent,
            AnyUri: self.any_uri_to_parent,
            ImageUri: self.imageuri_to_parent,
            ByteArray: self.not_supported,
            ComplexModelBase: self.complex_model_to_parent,
            Array: self.array_to_parent,
        })
コード例 #26
0
ファイル: to_cloth.py プロジェクト: spaceshipoperator/spyne
    def __init__(self, app=None, validator=None, mime_type=None,
                 ignore_uncap=False, ignore_wrappers=False):
        super(ToClothMixin, self).__init__(app=app, validator=validator,
                           mime_type=mime_type, ignore_uncap=ignore_uncap,
                                                ignore_wrappers=ignore_wrappers)

        self.rendering_handlers = cdict({
            ModelBase: self.model_base_to_cloth,
            AnyXml: self.element_to_cloth,
            AnyHtml: self.element_to_cloth,
            ComplexModelBase: self.complex_to_cloth,
        })
コード例 #27
0
ファイル: widget.py プロジェクト: cemrecan/neurons
    def __init__(self, label=True, type=None, hidden=False,
                                                           locale='en_US.utf8'):
        super(SimpleReadableNumberWidget, self).__init__(
                                          label=label, type=type, hidden=hidden)

        self.locale = locale

        self.serialization_handlers = cdict({
            Decimal: self.decimal_to_parent,
            Integer: self.integer_to_parent,
            ComplexModelBase: self.complex_model_to_parent,
        })
コード例 #28
0
ファイル: test_cdict.py プロジェクト: 66ru/spyne
    def test_cdict(self):
        d = cdict({A: "fun", object: "base"})

        assert d[A] == 'fun'
        assert d[B] == 'fun'
        assert d[C] == 'base'
        try:
            d[D]
        except KeyError:
            pass
        else:
            raise Exception("Must fail.")
コード例 #29
0
ファイル: django.py プロジェクト: simudream/spyne
class BaseDjangoFieldMapper(object):

    """Abstrace base class for field mappers."""

    _VALIDATOR_HANDLERS = cdict({
        MinLengthValidator: _handle_minlength,
        MaxLengthValidator: _handle_maxlength,
    })

    @staticmethod
    def is_field_nullable(field, **kwargs):
        """Return True if django field is nullable."""
        return field.null

    @staticmethod
    def is_field_blank(field, **kwargs):
        """Return True if django field is blank."""
        return field.blank

    def map(self, field, **kwargs):
        """Map field to spyne model.

        :param field: Django Field instance
        :param kwargs: Extra params to configure spyne model
        :returns: tuple (field attribute name, mapped spyne model)

        """
        params = kwargs.copy()

        self._process_validators(field.validators, params)

        nullable = self.is_field_nullable(field, **kwargs)
        blank = self.is_field_blank(field, **kwargs)
        required = not (field.has_default() or blank or field.primary_key)

        if field.has_default():
            params['default'] = field.get_default()

        spyne_model = self.get_spyne_model(field, **kwargs)
        customized_model = spyne_model(nullable=nullable,
                                       min_occurs=int(required), **params)

        return (field.attname, customized_model)

    def get_spyne_model(self, field, **kwargs):
        """Return spyne model for given Django field."""
        raise NotImplementedError

    def _process_validators(self, validators, params):
        for v in validators:
            handler = self._VALIDATOR_HANDLERS.get(type(v))
            if handler:
                handler(v, params)
コード例 #30
0
ファイル: microformat.py プロジェクト: zhuhj89/spyne
    def __init__(self, app=None, ignore_uncap=False, ignore_wrappers=False,
                       cloth=None, attr_name='spyne_id', root_attr_name='spyne',
                                                              cloth_parser=None,
                    root_tag='div', child_tag='div', field_name_attr='class',
                    field_name_tag=None, field_name_class='field_name'):
        """Protocol that returns the response object according to the "html
        microformat" specification. See
        https://en.wikipedia.org/wiki/Microformats for more info.

        The simple flavour is like the XmlDocument protocol, but returns data in
        <div> or <span> tags.

        :param app: A spyne.application.Application instance.
        :param validator: The validator to use. Ignored.
        :param root_tag: The type of the root tag that encapsulates the return
            data.
        :param child_tag: The type of the tag that encapsulates the fields of
            the returned object.
        :param field_name_attr: The name of the attribute that will contain the
            field names of the complex object children.
        """

        super(HtmlMicroFormat, self).__init__(app=app,
                     ignore_uncap=ignore_uncap, ignore_wrappers=ignore_wrappers,
                cloth=cloth, attr_name=attr_name, root_attr_name=root_attr_name,
                                                      cloth_parser=cloth_parser)

        assert root_tag in ('div', 'span')
        assert child_tag in ('div', 'span')
        assert field_name_attr in ('class', 'id')
        assert field_name_tag in (None, 'span', 'div')

        self.root_tag = root_tag
        self.child_tag = child_tag
        self.field_name_attr = field_name_attr
        self.field_name_tag = field_name_tag
        if field_name_tag is not None:
            self.field_name_tag = E(field_name_tag)
        self._field_name_class = field_name_class

        self.serialization_handlers = cdict({
            ModelBase: self.model_base_to_parent,
            AnyUri: self.anyuri_to_parent,
            AnyHtml: self.anyhtml_to_parent,
            ImageUri: self.imageuri_to_parent,
            ByteArray: self.not_supported,
            Attachment: self.not_supported,
            ComplexModelBase: self.complex_model_to_parent,
            Array: self.array_to_parent,
        })
コード例 #31
0
    def __init__(self, app=None, mime_type=None, ignore_uncap=False,
                                        ignore_wrappers=False, polymorphic=True):
        super(ToClothMixin, self).__init__(app=app, mime_type=mime_type,
                     ignore_uncap=ignore_uncap, ignore_wrappers=ignore_wrappers)

        self.polymorphic = polymorphic
        self.rendering_handlers = cdict({
            ModelBase: self.model_base_to_cloth,
            AnyXml: self.xml_to_cloth,
            Any: self.any_to_cloth,
            AnyHtml: self.html_to_cloth,
            AnyUri: self.anyuri_to_cloth,
            ComplexModelBase: self.complex_to_cloth,
        })
コード例 #32
0
ファイル: form_table.py プロジェクト: merveunlu/neurons
    def __init__(self, app=None, ignore_uncap=False, ignore_wrappers=False,
                       cloth=None, attr_name='spyne_id', root_attr_name='spyne',
                       cloth_parser=None, can_add=True, can_remove=True):

        super(HtmlFormTable, self).__init__(app=app,
                     ignore_uncap=ignore_uncap, ignore_wrappers=ignore_wrappers,
                cloth=cloth, attr_name=attr_name, root_attr_name=root_attr_name,
                                                      cloth_parser=cloth_parser)

        self.serialization_handlers = cdict({
            ModelBase: self.model_base_to_parent,
        })

        self.prot_form = HtmlForm()
        self.can_add = can_add
        self.can_remove = can_remove
コード例 #33
0
ファイル: form.py プロジェクト: yilmazalican/neurons
    def __init__(self, app=None, ignore_uncap=False, ignore_wrappers=False,
                cloth=None, cloth_parser=None, polymorphic=True, hier_delim='.',
                     doctype=None, label=True, asset_paths={}, placeholder=None,
                                         input_class=None, input_div_class=None,
                                     input_wrapper_class=None, label_class=None,
                                  action=None, method='POST', before_form=None):

        super(HtmlForm, self).__init__(app=app, doctype=doctype,
                     ignore_uncap=ignore_uncap, ignore_wrappers=ignore_wrappers,
                cloth=cloth, cloth_parser=cloth_parser, polymorphic=polymorphic,
                    hier_delim=hier_delim, label=label, asset_paths=asset_paths,
                    placeholder=placeholder, input_class=input_class,
                    input_div_class=input_div_class,
               input_wrapper_class=input_wrapper_class, label_class=label_class,
                          action=action, method=method, before_form=before_form)

        self.serialization_handlers = cdict({
            Date: self._check_simple(self.date_to_parent),
            Time: self._check_simple(self.time_to_parent),
            Uuid: self._check_simple(self.uuid_to_parent),
            Fault: self.fault_to_parent,
            Array: self.array_type_to_parent,
            AnyXml: self._check_simple(self.anyxml_to_parent),
            Integer: self._check_simple(self.integer_to_parent),
            Unicode: self._check_simple(self.unicode_to_parent),
            AnyHtml: self._check_simple(self.anyhtml_to_parent),
            Decimal: self._check_simple(self.decimal_to_parent),
            Boolean: self._check_simple(self.boolean_to_parent),
            Duration: self._check_simple(self.duration_to_parent),
            DateTime: self._check_simple(self.datetime_to_parent),
            ComplexModelBase: self.complex_model_to_parent,
        })

        self.hier_delim = hier_delim

        self.asset_paths = {
            ('jquery',): [_jstag("/assets/jquery/1.11.1/jquery.min.js")],
            ('jquery-ui',): [_jstag("/assets/jquery-ui/1.11.0/jquery-ui.min.js")],
            ('jquery-timepicker',): [
                _jstag("/assets/jquery-timepicker/jquery-ui-timepicker-addon.js"),
                _csstag("/assets/jquery-timepicker/jquery-ui-timepicker-addon.css"),
            ],
        }
        self.asset_paths.update(asset_paths)
        self.use_global_null_handler = False

        self.simple = SimpleRenderWidget(label=label)
コード例 #34
0
ファイル: to_parent.py プロジェクト: rtindru/spyne
    def __init__(self, app=None, validator=None, mime_type=None,
                                     ignore_uncap=False, ignore_wrappers=False):
        super(ToParentMixin, self).__init__(app=app, validator=validator,
                                 mime_type=mime_type, ignore_uncap=ignore_uncap,
                                 ignore_wrappers=ignore_wrappers)

        self.serialization_handlers = cdict({
            AnyXml: self.xml_to_parent,
            Fault: self.fault_to_parent,
            AnyDict: self.dict_to_parent,
            AnyHtml: self.html_to_parent,
            EnumBase: self.enum_to_parent,
            ModelBase: self.base_to_parent,
            ByteArray: self.byte_array_to_parent,
            ComplexModelBase: self.complex_to_parent,
            SchemaValidationError: self.schema_validation_error_to_parent,
        })
コード例 #35
0
ファイル: html.py プロジェクト: Bernie/spyne
    def __init__(self, app=None, validator=None, root_tag='div',
                 child_tag='div', field_name_attr='class', 
                 field_name_tag=None, field_name_class='field_name'):
        """Protocol that returns the response object as a html microformat. See
        https://en.wikipedia.org/wiki/Microformats for more info.

        The simple flavour is like the XmlDocument protocol, but returns data in
        <div> or <span> tags.

        :param app: A spyne.application.Application instance.
        :param validator: The validator to use. Ignored.
        :param root_tag: The type of the root tag that encapsulates the return
            data.
        :param child_tag: The type of the tag that encapsulates the fields of
            the returned object.
        :param field_name_attr: The name of the attribute that will contain the
            field names of the complex object children.
        :param field_type_attr: The name of the attribute that will contain the
            type names of the complex object children.
        :param with_field_names: Also return field names in the field tags
            inside separate tags.
        """

        HtmlBase.__init__(self, app, validator)

        assert root_tag in ('div', 'span')
        assert child_tag in ('div', 'span')
        assert field_name_attr in ('class', 'id')
        assert field_name_tag in (None, 'span', 'div')

        self.__root_tag = root_tag
        self.__child_tag = child_tag
        self.__field_name_attr = field_name_attr
        self._field_name_tag = field_name_tag
        if field_name_tag is not None:
            self._field_name_tag = getattr(E, field_name_tag)
        self._field_name_class = field_name_class

        self.serialization_handlers = cdict({
            ModelBase: self.serialize_model_base,
            ByteArray: not_supported,
            Attachment: not_supported,
            ComplexModelBase: self.serialize_complex_model,
            Array: self.serialize_array,
        })
コード例 #36
0
    def __init__(self,
                 app=None,
                 validator=None,
                 mime_type=None,
                 ignore_uncap=False,
                 ignore_wrappers=False,
                 polymorphic=True):
        super(ToParentMixin, self).__init__(app=app,
                                            validator=validator,
                                            mime_type=mime_type,
                                            ignore_uncap=ignore_uncap,
                                            ignore_wrappers=ignore_wrappers)

        self.polymorphic = polymorphic
        self.use_global_null_handler = True

        self.serialization_handlers = cdict({
            ModelBase:
            self.base_to_parent,
            AnyXml:
            self.xml_to_parent,
            AnyUri:
            self.anyuri_to_parent,
            AnyHtml:
            self.anyhtml_to_parent,
            ImageUri:
            self.imageuri_to_parent,
            AnyDict:
            self.dict_to_parent,
            AnyHtml:
            self.html_to_parent,
            Fault:
            self.fault_to_parent,
            EnumBase:
            self.enum_to_parent,
            ByteArray:
            self.byte_array_to_parent,
            ComplexModelBase:
            self.complex_to_parent,
            SchemaValidationError:
            self.schema_validation_error_to_parent,
        })
コード例 #37
0
ファイル: html.py プロジェクト: mangroovie/spyne
    def __init__(self,
                 app=None,
                 validator=None,
                 root_tag='div',
                 child_tag='div',
                 field_name_attr='class',
                 skip_depth=0):
        """Protocol that returns the response object as a html microformat. See
        https://en.wikipedia.org/wiki/Microformats for more info.

        The simple flavour is like the XmlDocument protocol, but returns data in
        <div> or <span> tags.

        :param app: A spyne.application.Application instance.
        :param validator: The validator to use. Ignored.
        :param root_tag: The type of the root tag that encapsulates the return
            data.
        :param child_tag: The type of the tag that encapsulates the fields of
            the returned object.
        :param field_name_attr: The name of the attribute that will contain the
            field names of the complex object children.
        :param field_type_attr: The name of the attribute that will contain the
            type names of the complex object children.
        """

        HtmlBase.__init__(self, app, validator, skip_depth)

        assert root_tag in ('div', 'span')
        assert child_tag in ('div', 'span')
        assert field_name_attr in ('class', 'id')

        self.__root_tag = root_tag
        self.__child_tag = child_tag
        self.__field_name_attr = field_name_attr

        self.serialization_handlers = cdict({
            ModelBase: self.serialize_model_base,
            ByteArray: not_supported,
            Attachment: not_supported,
            ComplexModelBase: self.serialize_complex_model,
            Array: self.serialize_array,
        })
コード例 #38
0
def _decode_pa_dict(d):
    """Decodes dict passed to prot_attrs.

    >>> _decode_pa_dict({})
    cdict({})
    >>> _decode_pa_dict({1: 2)})
    cdict({1: 2})
    >>> _decode_pa_dict({(1,2): 3)})
    cdict({1: 3, 2: 3})
    """

    retval = cdict()
    for k, v in d.items():
        if isinstance(k, tuple):
            for subk in k:
                retval[subk] = v

    for k, v in d.items():
        if not isinstance(k, tuple):
            retval[k] = v

    return retval
コード例 #39
0
ファイル: _base.py プロジェクト: jstuyck/spyne
def _decode_pa_dict(d):
    """Decodes dict passed to prot_attrs.

    >>> _decode_pa_dict({})
    cdict({})
    >>> _decode_pa_dict({1: 2)})
    cdict({1: 2})
    >>> _decode_pa_dict({(1,2): 3)})
    cdict({1: 3, 2: 3})
    """

    retval = cdict()
    for k, v in d.items():
        if isinstance(k, tuple):
            for subk in k:
                retval[subk] = v

    for k, v in d.items():
        if not isinstance(k, tuple):
            retval[k] = v

    return retval
コード例 #40
0
ファイル: html.py プロジェクト: shaung/spyne
    def __init__(
        self, app=None, validator=None, root_tag="div", child_tag="div", field_name_attr="class", skip_depth=0
    ):
        """Protocol that returns the response object as a html microformat. See
        https://en.wikipedia.org/wiki/Microformats for more info.

        The simple flavour is like the XmlObject protocol, but returns data in
        <div> or <span> tags.

        :param app: A spyne.application.Application instance.
        :param validator: The validator to use. Ignored.
        :param root_tag: The type of the root tag that encapsulates the return
            data.
        :param child_tag: The type of the tag that encapsulates the fields of
            the returned object.
        :param field_name_attr: The name of the attribute that will contain the
            field names of the complex object children.
        :param field_type_attr: The name of the attribute that will contain the
            type names of the complex object children.
        """

        HtmlBase.__init__(self, app, validator, skip_depth)

        assert root_tag in ("div", "span")
        assert child_tag in ("div", "span")
        assert field_name_attr in ("class", "id")

        self.__root_tag = root_tag
        self.__child_tag = child_tag
        self.__field_name_attr = field_name_attr

        self.serialization_handlers = cdict(
            {
                ModelBase: self.serialize_model_base,
                ByteArray: not_supported,
                Attachment: not_supported,
                ComplexModelBase: self.serialize_complex_model,
            }
        )
コード例 #41
0
ファイル: form_table.py プロジェクト: payingattention/neurons
    def __init__(self,
                 app=None,
                 ignore_uncap=False,
                 ignore_wrappers=False,
                 cloth=None,
                 attr_name='spyne_id',
                 root_attr_name='spyne',
                 cloth_parser=None):

        super(HtmlFormTable, self).__init__(app=app,
                                            ignore_uncap=ignore_uncap,
                                            ignore_wrappers=ignore_wrappers,
                                            cloth=cloth,
                                            attr_name=attr_name,
                                            root_attr_name=root_attr_name,
                                            cloth_parser=cloth_parser)

        self.serialization_handlers = cdict({
            ModelBase:
            self.model_base_to_parent,
        })

        self.prot_form = HtmlForm()
コード例 #42
0
    def __init__(self, app=None, validator=None,
                replace_null_with_default=True,
                xml_declaration=True,
                cleanup_namespaces=True, encoding=None, pretty_print=False,
                attribute_defaults=False,
                dtd_validation=False,
                load_dtd=False,
                no_network=True,
                ns_clean=False,
                recover=False,
                remove_blank_text=False,
                remove_pis=True,
                strip_cdata=True,
                resolve_entities=False,
                huge_tree=False,
                compact=True,
                binary_encoding=None,
                parse_xsi_type=True,
                polymorphic=False,
            ):

        super(XmlDocument, self).__init__(app, validator,
                                                binary_encoding=binary_encoding)

        self.xml_declaration = xml_declaration
        self.cleanup_namespaces = cleanup_namespaces
        self.replace_null_with_default = replace_null_with_default

        if encoding is None:
            self.encoding = 'UTF-8'
        else:
            self.encoding = encoding

        self.polymorphic = polymorphic
        self.pretty_print = pretty_print
        self.parse_xsi_type = parse_xsi_type

        self.serialization_handlers = cdict({
            AnyXml: self.xml_to_parent,
            Any: self.xml_to_parent,
            Fault: self.fault_to_parent,
            AnyDict: self.dict_to_parent,
            AnyHtml: self.html_to_parent,
            EnumBase: self.enum_to_parent,
            XmlData: self.xmldata_to_parent,
            ModelBase: self.modelbase_to_parent,
            ByteArray: self.byte_array_to_parent,
            Attachment: self.attachment_to_parent,
            XmlAttribute: self.xmlattribute_to_parent,
            ComplexModelBase: self.complex_to_parent,
            SchemaValidationError: self.schema_validation_error_to_parent,
        })

        self.deserialization_handlers = cdict({
            AnyHtml: self.html_from_element,
            AnyXml: self.xml_from_element,
            Any: self.xml_from_element,
            Array: self.array_from_element,
            Fault: self.fault_from_element,
            AnyDict: self.dict_from_element,
            EnumBase: self.enum_from_element,
            ModelBase: self.base_from_element,
            Unicode: self.unicode_from_element,
            Iterable: self.iterable_from_element,
            ByteArray: self.byte_array_from_element,
            Attachment: self.attachment_from_element,
            ComplexModelBase: self.complex_from_element,
        })

        self.parser_kwargs = dict(
            attribute_defaults=attribute_defaults,
            dtd_validation=dtd_validation,
            load_dtd=load_dtd,
            no_network=no_network,
            ns_clean=ns_clean,
            recover=recover,
            remove_blank_text=remove_blank_text,
            remove_comments=True,
            remove_pis=remove_pis,
            strip_cdata=strip_cdata,
            resolve_entities=resolve_entities,
            huge_tree=huge_tree,
            compact=compact,
            encoding=encoding,
        )
コード例 #43
0
ファイル: model.py プロジェクト: infoxchange/spyne
from spyne.util.etreeconv import dict_to_etree
from spyne.util.six import string_types
from spyne.protocol.xml import XmlDocument
_prot = XmlDocument()

XSD = lambda s: '{%s}%s' % (_ns_xsd, s)

# In Xml Schema, some customizations do not need a class to be extended -- they
# are specified in-line in the parent class definition, like nullable or
# min_occurs. The dict below contains list of parameters that do warrant a
# proper subclass definition for each type. This must be updated as the Xml
# Schema implementation makes progress.
ATTR_NAMES = cdict({
    ModelBase: set(['values']),
    Decimal: set(['pattern', 'gt', 'ge', 'lt', 'le', 'values', 'total_digits',
                                                            'fraction_digits']),
    Integer: set(['pattern', 'gt', 'ge', 'lt', 'le', 'values', 'total_digits']),
    Unicode: set(['values', 'min_len', 'max_len', 'pattern']),
})

def xml_attribute_add(cls, name, element, document):
    element.set('name', name)
    element.set('type', cls.type.get_type_name_ns(document.interface))

    if cls._use is not None:
        element.set('use', cls._use)

    d = cls.type.Attributes.default

    if d is not None:
        element.set('default', _prot.to_string(cls.type, d))
コード例 #44
0
ファイル: _outbase.py プロジェクト: sirboldilox/spyne
    def __init__(self,
                 app=None,
                 mime_type=None,
                 ignore_uncap=False,
                 ignore_wrappers=False,
                 binary_encoding=None):

        super(OutProtocolBase, self).__init__(app=app,
                                              mime_type=mime_type,
                                              ignore_wrappers=ignore_wrappers)

        self.ignore_uncap = ignore_uncap
        self.message = None
        self.binary_encoding = binary_encoding

        if self.binary_encoding is None:
            self.binary_encoding = self.default_binary_encoding

        if mime_type is not None:
            self.mime_type = mime_type

        self._to_bytes_handlers = cdict({
            ModelBase:
            self.model_base_to_bytes,
            File:
            self.file_to_bytes,
            Time:
            self.time_to_bytes,
            Uuid:
            self.uuid_to_bytes,
            Null:
            self.null_to_bytes,
            Double:
            self.double_to_bytes,
            AnyXml:
            self.any_xml_to_bytes,
            Unicode:
            self.unicode_to_bytes,
            Boolean:
            self.boolean_to_bytes,
            Decimal:
            self.decimal_to_bytes,
            Integer:
            self.integer_to_bytes,
            AnyHtml:
            self.any_html_to_bytes,
            DateTime:
            self.datetime_to_bytes,
            Duration:
            self.duration_to_bytes,
            ByteArray:
            self.byte_array_to_bytes,
            XmlAttribute:
            self.xmlattribute_to_bytes,
            ComplexModelBase:
            self.complex_model_base_to_bytes,
        })

        self._to_unicode_handlers = cdict({
            ModelBase:
            self.model_base_to_unicode,
            File:
            self.file_to_unicode,
            Time:
            self.time_to_bytes,
            Uuid:
            self.uuid_to_bytes,
            Null:
            self.null_to_bytes,
            Double:
            self.double_to_bytes,
            AnyXml:
            self.any_xml_to_unicode,
            AnyUri:
            self.any_uri_to_unicode,
            AnyDict:
            self.any_dict_to_unicode,
            AnyHtml:
            self.any_html_to_unicode,
            Unicode:
            self.unicode_to_unicode,
            Boolean:
            self.boolean_to_bytes,
            Decimal:
            self.decimal_to_bytes,
            Integer:
            self.integer_to_bytes,
            # FIXME: Would we need a to_unicode for localized dates?
            DateTime:
            self.datetime_to_bytes,
            Duration:
            self.duration_to_bytes,
            ByteArray:
            self.byte_array_to_unicode,
            XmlAttribute:
            self.xmlattribute_to_unicode,
            ComplexModelBase:
            self.complex_model_base_to_bytes,
        })

        self._to_bytes_iterable_handlers = cdict({
            File:
            self.file_to_bytes_iterable,
            ByteArray:
            self.byte_array_to_bytes_iterable,
            ModelBase:
            self.model_base_to_bytes_iterable,
            SimpleModel:
            self.simple_model_to_bytes_iterable,
            ComplexModelBase:
            self.complex_model_to_bytes_iterable,
        })
コード例 #45
0
MAP = cdict({
    ModelBase:
    cdict({
        object: lambda _: _,
        bytes: lambda _: _.strip(),
        unicode: lambda _: _.strip(),
    }),
    Decimal:
    cdict({
        int: lambda _: D(_),
        bytes: lambda s: None if s.strip() == '' else D(s.strip()),
        unicode: lambda s: None if s.strip() == u'' else D(s.strip()),
    }),
    Integer:
    cdict({
        int: lambda _: _,
        bytes: lambda s: None if s.strip() == '' else int(s.strip()),
        unicode: lambda s: None if s.strip() == u'' else int(s.strip()),
    }),
    Date:
    cdict({
        object:
        lambda _: _,
        bytes:
        lambda s: None if s.strip() in
        ('', '0000-00-00') else _prot.date_from_string(Date, s.strip()),
        unicode:
        lambda s: None if s.strip() in
        (u'', u'0000-00-00') else _prot.date_from_string(Date, s.strip()),
    }),
    DateTime:
    cdict({
        object:
        lambda _: _,
        bytes:
        lambda s: None if s.strip() in
        ('', '0000-00-00 00:00:00') else _prot.datetime_from_string(
            DateTime, s.strip()),
        unicode:
        lambda s: None if s.strip() in
        (u'', u'0000-00-00 00:00:00') else _prot.datetime_from_string(
            DateTime, s.strip()),
    }),
    IpAddress:
    cdict({
        object: lambda _: _,
        bytes: lambda s: None if s.strip() == '' else s.strip(),
        unicode: lambda s: None if s.strip() == u'' else s.strip(),
    })
})
コード例 #46
0
ファイル: dynint.py プロジェクト: wfmexpert/spyne
from spyne import Integer, ModelBase
from spyne.util.cdict import cdict

MAP = cdict({
    ModelBase:
    cdict({
        object: lambda _: _,
        basestring: lambda _: _
    }),
    Integer:
    cdict({
        int: lambda _: _,
        basestring: lambda s: None if s == '' else int(s),
    })
})


def dynamic_init(cls, **kwargs):
    fti = cls.get_flat_type_info(cls)
    retval = cls()

    for k, v in fti.items():
        if k in kwargs:
            subval = kwargs[k]
            t = MAP[v]
            setattr(retval, k, t[type(subval)](subval))

    return retval
コード例 #47
0
ファイル: cli.py プロジェクト: drlatech/neurons
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

import argparse
import os.path

from gettext import gettext
from decimal import Decimal as D

from spyne import Boolean, Unicode, Integer, Decimal, ComplexModelBase, Array
from spyne.protocol import get_cls_attrs
from spyne.util import six
from spyne.util.cdict import cdict

ARGTYPE_MAP = cdict({
    Integer: int,
    Decimal: D,
})

config_overrides = set()


class ArgumentParser(argparse.ArgumentParser):
    def parse_args(self, args=None, namespace=None):
        args, argv = self.parse_known_args(args, namespace)

        if len(argv) > 0:
            newargv = []
            for a in argv:
                if a.startswith("--assets-"):
                    opt, val = a.split("=", 2)
                    val = os.path.abspath(val)
コード例 #48
0
ファイル: _base.py プロジェクト: pxiol/spyne
    def __init__(self, app=None, validator=None, mime_type=None,
                                       ignore_uncap=False, ignore_wrappers=False):
        self.__app = None
        self.set_app(app)

        self.validator = None
        self.set_validator(validator)

        self.event_manager = EventManager(self)
        self.ignore_uncap = ignore_uncap
        self.ignore_wrappers = ignore_wrappers
        self.message = None

        if mime_type is not None:
            self.mime_type = mime_type

        self._to_string_handlers = cdict({
            ModelBase: self.model_base_to_string,
            Time: self.time_to_string,
            Uuid: self.uuid_to_string,
            Null: self.null_to_string,
            Double: self.double_to_string,
            AnyXml: self.any_xml_to_string,
            Unicode: self.unicode_to_string,
            Boolean: self.boolean_to_string,
            Decimal: self.decimal_to_string,
            Integer: self.integer_to_string,
            AnyHtml: self.any_html_to_string,
            DateTime: self.datetime_to_string,
            Duration: self.duration_to_string,
            ByteArray: self.byte_array_to_string,
            Attachment: self.attachment_to_string,
            XmlAttribute: self.xmlattribute_to_string,
            ComplexModelBase: self.complex_model_base_to_string,
        })

        self._to_string_iterable_handlers = cdict({
            File: self.file_to_string_iterable,
            ByteArray: self.byte_array_to_string_iterable,
            ModelBase: self.model_base_to_string_iterable,
            SimpleModel: self.simple_model_to_string_iterable,
            ComplexModelBase: self.complex_model_to_string_iterable,
        })

        self._from_string_handlers = cdict({
            Null: self.null_from_string,
            Time: self.time_from_string,
            Date: self.date_from_string,
            Uuid: self.uuid_from_string,
            File: self.file_from_string,
            Double: self.double_from_string,
            String: self.string_from_string,
            AnyXml: self.any_xml_from_string,
            Boolean: self.boolean_from_string,
            Integer: self.integer_from_string,
            Unicode: self.unicode_from_string,
            Decimal: self.decimal_from_string,
            AnyHtml: self.any_html_from_string,
            DateTime: self.datetime_from_string,
            Duration: self.duration_from_string,
            ByteArray: self.byte_array_from_string,
            ModelBase: self.model_base_from_string,
            Attachment: self.attachment_from_string,
            ComplexModelBase: self.complex_model_base_from_string
        })

        self._datetime_dsmap = {
            None: self._datetime_from_string,
            'sec': self._datetime_from_sec,
            'sec_float': self._datetime_from_sec_float,
            'msec': self._datetime_from_msec,
            'msec_float': self._datetime_from_msec_float,
            'usec': self._datetime_from_usec,
        }
コード例 #49
0
ファイル: _base.py プロジェクト: pxiol/spyne
from spyne.interface import InterfaceDocumentBase

from spyne.interface.xml_schema.model import byte_array_add
from spyne.interface.xml_schema.model import simple_add
from spyne.interface.xml_schema.model import complex_add
from spyne.interface.xml_schema.model import fault_add
from spyne.interface.xml_schema.model import enum_add

from spyne.interface.xml_schema.model import simple_get_restriction_tag
from spyne.interface.xml_schema.model import unicode_get_restriction_tag
from spyne.interface.xml_schema.model import Tget_range_restriction_tag

_add_handlers = cdict({
    object: lambda interface, cls, tags: None,
    ByteArray: byte_array_add,
    SimpleModel: simple_add,
    ComplexModelBase: complex_add,
    Fault: fault_add,
    EnumBase: enum_add,
})

_get_restriction_tag_handlers = cdict({
    object:
    lambda self, cls: None,
    SimpleModel:
    simple_get_restriction_tag,
    Unicode:
    unicode_get_restriction_tag,
    Decimal:
    Tget_range_restriction_tag(Decimal),
    DateTime:
    Tget_range_restriction_tag(DateTime),
コード例 #50
0
class ProtocolBase(object):
    """This is the abstract base class for all protocol implementations. Child
    classes can implement only the required subset of the public methods.

    An output protocol must implement :func:`serialize` and
    :func:`create_out_string`.

    An input protocol must implement :func:`create_in_document`,
    :func:`decompose_incoming_envelope` and :func:`deserialize`.

    The ProtocolBase class supports the following events:

    * ``before_deserialize``:
      Called before the deserialization operation is attempted.

    * ``after_deserialize``:
      Called after the deserialization operation is finished.

    * ``before_serialize``:
      Called before after the serialization operation is attempted.

    * ``after_serialize``:
      Called after the serialization operation is finished.

    The arguments the constructor takes are as follows:

    :param app: The application this protocol belongs to.
    :param validator: The type of validation this protocol should do on
        incoming data.
    :param mime_type: The mime_type this protocol should set for transports
        that support this. This is a quick way to override the mime_type by
        default instead of subclassing the releavant protocol implementation.
    :param skip_depth: Number of wrapper classes to ignore. This is
        typically one of (0, 1, 2) but higher numbers may also work for your
        case.
    :param ignore_uncap: Silently ignore cases when the protocol is not capable
        of serializing return values instead of raising a TypeError.
    """

    __metaclass__ = ProtocolBaseMeta

    allowed_http_verbs = None
    mime_type = 'application/octet-stream'

    SOFT_VALIDATION = type("Soft", (object, ), {})
    REQUEST = type("Request", (object, ), {})
    RESPONSE = type("Response", (object, ), {})

    type = set()
    """Set that contains keywords about a protocol."""

    default_binary_encoding = None

    _to_string_handlers = cdict({
        ModelBase:
        lambda cls, value: cls.to_string(value),
        Null:
        null_to_string,
        AnyXml:
        any_xml_to_string,
        Unicode:
        unicode_to_string,
        Decimal:
        decimal_to_string,
        Double:
        double_to_string,
        Integer:
        integer_to_string,
        Time:
        time_to_string,
        DateTime:
        datetime_to_string,
        Duration:
        duration_to_string,
        Boolean:
        boolean_to_string,
        ByteArray:
        byte_array_to_string,
        Attachment:
        attachment_to_string,
        ComplexModelBase:
        complex_model_base_to_string,
    })

    _to_string_iterable_handlers = cdict({
        ModelBase:
        lambda prot, cls, value: cls.to_string_iterable(value),
        SimpleModel:
        lambda prot, cls, value: (prot._to_string_handlers[cls](cls, value), ),
        ByteArray:
        byte_array_to_string_iterable,
        File:
        file_to_string_iterable,
    })

    _from_string_handlers = cdict({
        Null:
        null_from_string,
        AnyXml:
        any_xml_from_string,
        Unicode:
        unicode_from_string,
        String:
        string_from_string,
        Decimal:
        decimal_from_string,
        Double:
        double_from_string,
        Integer:
        integer_from_string,
        Time:
        time_from_string,
        DateTime:
        datetime_from_string,
        Date:
        date_from_string,
        Duration:
        duration_from_string,
        Boolean:
        boolean_from_string,
        ByteArray:
        byte_array_from_string,
        File:
        file_from_string,
        Attachment:
        attachment_from_string,
        ComplexModelBase:
        complex_model_base_from_string
    })

    _to_dict_handlers = cdict({
        ModelBase: lambda cls, value: cls.to_dict(value),
        ComplexModelBase: complex_model_base_to_dict,
        Fault: fault_to_dict,
    })

    def __init__(self,
                 app=None,
                 validator=None,
                 mime_type=None,
                 skip_depth=0,
                 ignore_uncap=False):
        self.__app = None
        self.validator = None

        self.set_app(app)
        self.event_manager = EventManager(self)
        self.set_validator(validator)
        self.skip_depth = skip_depth
        self.ignore_uncap = ignore_uncap
        if mime_type is not None:
            self.mime_type = mime_type

    @property
    def app(self):
        return self.__app

    def set_app(self, value):
        assert self.__app is None, "One protocol instance should belong to one " \
                                   "application instance."
        self.__app = value

    def create_in_document(self, ctx, in_string_encoding=None):
        """Uses ``ctx.in_string`` to set ``ctx.in_document``."""

    def decompose_incoming_envelope(self, ctx, message):
        """Sets the ``ctx.method_request_string``, ``ctx.in_body_doc``,
        ``ctx.in_header_doc`` and ``ctx.service`` properties of the ctx object,
        if applicable.
        """

    def deserialize(self, ctx):
        """Takes a MethodContext instance and a string containing ONE document
        instance in the ``ctx.in_string`` attribute.

        Returns the corresponding native python object in the ctx.in_object
        attribute.
        """

    def serialize(self, ctx):
        """Takes a MethodContext instance and the object to be serialized in the
        ctx.out_object attribute.

        Returns the corresponding document structure in the ctx.out_document
        attribute.
        """

    def create_out_string(self, ctx, out_string_encoding=None):
        """Uses ctx.out_document to set ctx.out_string"""

    def validate_document(self, payload):
        """Method to be overriden to perform any sort of custom input
        validation on the parsed input document.
        """

    def generate_method_contexts(self, ctx):
        """Generates MethodContext instances for every callable assigned to the
        given method handle.

        The first element in the returned list is always the primary method
        context whereas the rest are all auxiliary method contexts.
        """

        call_handles = self.get_call_handles(ctx)
        if len(call_handles) == 0:
            raise ResourceNotFoundError('Method %r not found.' %
                                        ctx.method_request_string)

        retval = []
        for sc, d in call_handles:
            c = copy(ctx)

            assert d != None

            c.descriptor = d
            c.service_class = sc

            retval.append(c)

        return retval

    def get_call_handles(self, ctx):
        """Method to be overriden to perform any sort of custom method mapping
        using any data in the method context. Returns a list of contexts.
        Can return multiple contexts if a method_request_string matches more
        than one function. (This is called the fanout mode.)
        """

        name = ctx.method_request_string
        if not name.startswith("{"):
            name = '{%s}%s' % (self.app.interface.get_tns(), name)

        call_handles = self.app.interface.service_method_map.get(name, [])

        return call_handles

    def fault_to_http_response_code(self, fault):
        """Special function to convert native Python exceptions to Http response
        codes.
        """

        if isinstance(fault, RequestTooLongError):
            return HTTP_413
        if isinstance(fault, ResourceNotFoundError):
            return HTTP_404
        if isinstance(fault, RequestNotAllowed):
            return HTTP_405
        if isinstance(fault, Fault) and (fault.faultcode.startswith('Client.')
                                         or fault.faultcode == 'Client'):
            return HTTP_400
        else:
            return HTTP_500

    def set_validator(self, validator):
        """You must override this function if you want your protocol to support
        validation."""

        assert validator is None

        self.validator = None

    @classmethod
    def from_string(cls, class_, string):
        handler = cls._from_string_handlers[class_]
        return handler(class_, string)

    @classmethod
    def to_string(cls, class_, value):
        handler = cls._to_string_handlers[class_]
        return handler(class_, value)

    @classmethod
    def to_string_iterable(cls, class_, value):
        handler = cls._to_string_iterable_handlers[class_]
        return handler(cls, class_, value)

    @classmethod
    def to_dict(cls, class_, value):
        handler = cls._to_dict_handlers[class_]
        return handler(class_, value)
コード例 #51
0
    def __init__(
        self,
        app=None,
        validator=None,
        xml_declaration=True,
        cleanup_namespaces=True,
        encoding=None,
        pretty_print=False,
        attribute_defaults=False,
        dtd_validation=False,
        load_dtd=False,
        no_network=True,
        ns_clean=False,
        recover=False,
        remove_blank_text=False,
        remove_pis=True,
        strip_cdata=True,
        resolve_entities=False,
        huge_tree=False,
        compact=True,
    ):
        super(XmlDocument, self).__init__(app, validator)
        self.xml_declaration = xml_declaration
        self.cleanup_namespaces = cleanup_namespaces

        if encoding is None:
            self.encoding = 'UTF-8'
        else:
            self.encoding = encoding

        self.pretty_print = pretty_print

        self.serialization_handlers = cdict({
            AnyXml:
            self.xml_to_parent,
            Fault:
            self.fault_to_parent,
            AnyDict:
            self.dict_to_parent,
            AnyHtml:
            self.html_to_parent,
            EnumBase:
            self.enum_to_parent,
            ModelBase:
            self.base_to_parent,
            ByteArray:
            self.byte_array_to_parent,
            Attachment:
            self.attachment_to_parent,
            XmlAttribute:
            self.xmlattribute_to_parent,
            ComplexModelBase:
            self.complex_to_parent,
            SchemaValidationError:
            self.schema_validation_error_to_parent,
        })

        self.deserialization_handlers = cdict({
            AnyXml:
            self.xml_from_element,
            Array:
            self.array_from_element,
            Fault:
            self.fault_from_element,
            AnyDict:
            self.dict_from_element,
            EnumBase:
            self.enum_from_element,
            ModelBase:
            self.base_from_element,
            Unicode:
            self.unicode_from_element,
            Iterable:
            self.iterable_from_element,
            ByteArray:
            self.byte_array_from_element,
            Attachment:
            self.attachment_from_element,
            ComplexModelBase:
            self.complex_from_element,
        })

        self.log_messages = (logger.level == logging.DEBUG)
        self.parser_kwargs = dict(
            attribute_defaults=attribute_defaults,
            dtd_validation=dtd_validation,
            load_dtd=load_dtd,
            no_network=no_network,
            ns_clean=ns_clean,
            recover=recover,
            remove_blank_text=remove_blank_text,
            remove_comments=True,
            remove_pis=remove_pis,
            strip_cdata=strip_cdata,
            resolve_entities=resolve_entities,
            huge_tree=huge_tree,
            compact=compact,
            encoding=encoding,
        )
コード例 #52
0
ファイル: model.py プロジェクト: junneyang/spyne
_prot = XmlDocument()

XSD = lambda s: '{%s}%s' % (_ns_xsd, s)

# In Xml Schema, some customizations do not need a class to be extended -- they
# are specified in-line in the parent class definition, like nullable or
# min_occurs. The dict below contains list of parameters that do warrant a
# proper subclass definition for each type. This must be updated as the Xml
# Schema implementation makes progress.
ATTR_NAMES = cdict({
    ModelBase:
    set(['values']),
    Decimal:
    set([
        'pattern', 'gt', 'ge', 'lt', 'le', 'values', 'total_digits',
        'fraction_digits'
    ]),
    Integer:
    set(['pattern', 'gt', 'ge', 'lt', 'le', 'values', 'total_digits']),
    Unicode:
    set(['values', 'min_len', 'max_len', 'pattern']),
})


def xml_attribute_add(cls, name, element, document):
    element.set('name', name)
    element.set('type', cls.type.get_type_name_ns(document.interface))

    if cls._use is not None:
        element.set('use', cls._use)
コード例 #53
0
ファイル: dyninit.py プロジェクト: umarmughal824/spyne
MAP = cdict({
    ModelBase: cdict({
        object: lambda _: _,
        bytes: lambda _: _.strip(),
        unicode: lambda _: _.strip(),
    }),

    Decimal: cdict({
        D: lambda d: d,
        int: lambda i: D(i),
        bytes: lambda s: None if s.strip() == '' else D(s.strip()),
        unicode: lambda s: None if s.strip() == u'' else D(s.strip()),
    }),

    Boolean: cdict({
        D: lambda d: _bool_from_int(int(d)),
        int: _bool_from_int,
        bytes: _bool_from_bytes,
        unicode: _bool_from_str,
    }),

    Integer: cdict({
        D: lambda _: _,
        int: lambda _: _,
        bytes: lambda s: None if s.strip() == '' else int(s.strip()),
        unicode: lambda s: None if s.strip() == u'' else int(s.strip()),
    }),

    Date: cdict({
        date: lambda _: _,
        datetime: lambda _: _.date(),
        object: lambda _:_,
        bytes: lambda s: None if s.strip() in ('', '0000-00-00')
                                  else _prot.date_from_unicode(Date, s.strip()),
        unicode: lambda s: None if s.strip() in (u'', u'0000-00-00')
                                  else _prot.date_from_unicode(Date, s.strip()),
    }),

    DateTime: cdict({
        date: lambda _: datetime(date.year, date.month, date.day),
        datetime: lambda _: _,
        object: lambda _:_,
        bytes: lambda s: None if s.strip() in ('', '0000-00-00 00:00:00')
                          else _prot.datetime_from_unicode(DateTime, s.strip()),
        unicode: lambda s: None if s.strip() in (u'', u'0000-00-00 00:00:00')
                          else _prot.datetime_from_unicode(DateTime, s.strip()),
    }),

    IpAddress: cdict({
        object: lambda _: _,
        bytes: lambda s: None if s.strip() == '' else s.strip(),
        unicode: lambda s: None if s.strip() == u'' else s.strip(),
    })
})
コード例 #54
0
ファイル: xml.py プロジェクト: cdcanasg/spyne
    def __init__(self, app=None, validator=None,
                replace_null_with_default=True,
                xml_declaration=True,
                cleanup_namespaces=True, encoding=None, pretty_print=False,
                attribute_defaults=False,
                dtd_validation=False,
                load_dtd=False,
                no_network=True,
                ns_clean=False,
                recover=False,
                remove_blank_text=False,
                remove_pis=True,
                strip_cdata=True,
                resolve_entities=False,
                huge_tree=False,
                compact=True,
                binary_encoding=None,
                parse_xsi_type=True,
                polymorphic=False,
            ):

        super(XmlDocument, self).__init__(app, validator,
                                                binary_encoding=binary_encoding)

        self.validation_schema = None
        self.xml_declaration = xml_declaration
        self.cleanup_namespaces = cleanup_namespaces
        self.replace_null_with_default = replace_null_with_default

        if encoding is None:
            self.encoding = 'UTF-8'
        else:
            self.encoding = encoding

        self.polymorphic = polymorphic
        self.pretty_print = pretty_print
        self.parse_xsi_type = parse_xsi_type

        self.serialization_handlers = cdict({
            Any: self.any_to_parent,
            Fault: self.fault_to_parent,
            EnumBase: self.enum_to_parent,
            AnyXml: self.any_xml_to_parent,
            XmlData: self.xmldata_to_parent,
            AnyDict: self.any_dict_to_parent,
            AnyHtml: self.any_html_to_parent,
            ModelBase: self.modelbase_to_parent,
            ByteArray: self.byte_array_to_parent,
            ComplexModelBase: self.complex_to_parent,
            XmlAttribute: self.xmlattribute_to_parent,
            SchemaValidationError: self.schema_validation_error_to_parent,
        })

        self.deserialization_handlers = cdict({
            AnyHtml: self.html_from_element,
            AnyXml: self.xml_from_element,
            Any: self.xml_from_element,
            Array: self.array_from_element,
            Fault: self.fault_from_element,
            AnyDict: self.dict_from_element,
            EnumBase: self.enum_from_element,
            ModelBase: self.base_from_element,
            Unicode: self.unicode_from_element,
            Iterable: self.iterable_from_element,
            ByteArray: self.byte_array_from_element,
            ComplexModelBase: self.complex_from_element,
        })

        self.parser_kwargs = dict(
            attribute_defaults=attribute_defaults,
            dtd_validation=dtd_validation,
            load_dtd=load_dtd,
            no_network=no_network,
            ns_clean=ns_clean,
            recover=recover,
            remove_blank_text=remove_blank_text,
            remove_comments=True,
            remove_pis=remove_pis,
            strip_cdata=strip_cdata,
            resolve_entities=resolve_entities,
            huge_tree=huge_tree,
            compact=compact,
            encoding=encoding,
        )
コード例 #55
0
ファイル: _outbase.py プロジェクト: Bzisch/spyne
    def __init__(self, app=None, mime_type=None, ignore_uncap=False,
                                   ignore_wrappers=False, binary_encoding=None):

        super(OutProtocolBase, self).__init__(app=app, mime_type=mime_type,
                                                ignore_wrappers=ignore_wrappers)

        self.ignore_uncap = ignore_uncap
        self.message = None
        self.binary_encoding = binary_encoding

        if self.binary_encoding is None:
            self.binary_encoding = self.default_binary_encoding

        if mime_type is not None:
            self.mime_type = mime_type

        self._to_bytes_handlers = cdict({
            ModelBase: self.model_base_to_bytes,
            File: self.file_to_bytes,
            Time: self.time_to_bytes,
            Uuid: self.uuid_to_bytes,
            Null: self.null_to_bytes,
            Double: self.double_to_bytes,
            AnyXml: self.any_xml_to_bytes,
            Unicode: self.unicode_to_bytes,
            Boolean: self.boolean_to_bytes,
            Decimal: self.decimal_to_bytes,
            Integer: self.integer_to_bytes,
            AnyHtml: self.any_html_to_bytes,
            DateTime: self.datetime_to_bytes,
            Duration: self.duration_to_bytes,
            ByteArray: self.byte_array_to_bytes,
            Attachment: self.attachment_to_bytes,
            XmlAttribute: self.xmlattribute_to_bytes,
            ComplexModelBase: self.complex_model_base_to_bytes,
        })

        self._to_unicode_handlers = cdict({
            ModelBase: self.model_base_to_unicode,
            File: self.file_to_unicode,
            Time: self.time_to_bytes,
            Uuid: self.uuid_to_bytes,
            Null: self.null_to_bytes,
            Double: self.double_to_bytes,
            AnyXml: self.any_xml_to_unicode,
            Unicode: self.unicode_to_unicode,
            Boolean: self.boolean_to_bytes,
            Decimal: self.decimal_to_bytes,
            Integer: self.integer_to_bytes,
            AnyHtml: self.any_html_to_unicode,
            # FIXME: Would we need a to_unicode for localized dates?
            DateTime: self.datetime_to_bytes,
            Duration: self.duration_to_bytes,
            ByteArray: self.byte_array_to_unicode,
            XmlAttribute: self.xmlattribute_to_unicode,
            ComplexModelBase: self.complex_model_base_to_bytes,
        })

        self._to_bytes_iterable_handlers = cdict({
            File: self.file_to_bytes_iterable,
            ByteArray: self.byte_array_to_bytes_iterable,
            ModelBase: self.model_base_to_bytes_iterable,
            SimpleModel: self.simple_model_to_bytes_iterable,
            ComplexModelBase: self.complex_model_to_bytes_iterable,
        })
コード例 #56
0
ファイル: _base.py プロジェクト: armandomeeuwenoord/spyne
    def __init__(self,
                 app=None,
                 validator=None,
                 mime_type=None,
                 ignore_uncap=False,
                 ignore_wrappers=False,
                 binary_encoding=None):
        self.validator = None
        self.set_validator(validator)

        self.__app = None
        self.set_app(app)

        self._attrcache = WeakKeyDictionary()

        self.event_manager = EventManager(self)
        self.ignore_uncap = ignore_uncap
        self.ignore_wrappers = ignore_wrappers
        self.message = None
        self.binary_encoding = binary_encoding
        if self.binary_encoding is None:
            self.binary_encoding = self.default_binary_encoding

        if mime_type is not None:
            self.mime_type = mime_type

        self._to_string_handlers = cdict({
            ModelBase:
            self.model_base_to_string,
            File:
            self.file_to_string,
            Time:
            self.time_to_string,
            Uuid:
            self.uuid_to_string,
            Null:
            self.null_to_string,
            Double:
            self.double_to_string,
            AnyXml:
            self.any_xml_to_string,
            Unicode:
            self.unicode_to_string,
            Boolean:
            self.boolean_to_string,
            Decimal:
            self.decimal_to_string,
            Integer:
            self.integer_to_string,
            AnyHtml:
            self.any_html_to_string,
            DateTime:
            self.datetime_to_string,
            Duration:
            self.duration_to_string,
            ByteArray:
            self.byte_array_to_string,
            Attachment:
            self.attachment_to_string,
            XmlAttribute:
            self.xmlattribute_to_string,
            ComplexModelBase:
            self.complex_model_base_to_string,
        })

        self._to_unicode_handlers = cdict({
            ModelBase:
            self.model_base_to_unicode,
            File:
            self.file_to_unicode,
            Time:
            self.time_to_string,
            Uuid:
            self.uuid_to_string,
            Null:
            self.null_to_string,
            Double:
            self.double_to_string,
            AnyXml:
            self.any_xml_to_unicode,
            Unicode:
            self.unicode_to_unicode,
            Boolean:
            self.boolean_to_string,
            Decimal:
            self.decimal_to_string,
            Integer:
            self.integer_to_string,
            AnyHtml:
            self.any_html_to_unicode,
            # FIXME: Would we need a to_unicode for localized dates?
            DateTime:
            self.datetime_to_string,
            Duration:
            self.duration_to_string,
            ByteArray:
            self.byte_array_to_unicode,
            XmlAttribute:
            self.xmlattribute_to_unicode,
            ComplexModelBase:
            self.complex_model_base_to_string,
        })

        self._to_string_iterable_handlers = cdict({
            File:
            self.file_to_string_iterable,
            ByteArray:
            self.byte_array_to_string_iterable,
            ModelBase:
            self.model_base_to_string_iterable,
            SimpleModel:
            self.simple_model_to_string_iterable,
            ComplexModelBase:
            self.complex_model_to_string_iterable,
        })

        fsh = {
            Null: self.null_from_string,
            Time: self.time_from_string,
            Date: self.date_from_string,
            Uuid: self.uuid_from_string,
            File: self.file_from_string,
            Array: self.array_from_string,
            Double: self.double_from_string,
            String: self.string_from_string,
            AnyXml: self.any_xml_from_string,
            Boolean: self.boolean_from_string,
            Integer: self.integer_from_string,
            Unicode: self.unicode_from_string,
            Decimal: self.decimal_from_string,
            AnyHtml: self.any_html_from_string,
            DateTime: self.datetime_from_string,
            Duration: self.duration_from_string,
            ByteArray: self.byte_array_from_string,
            EnumBase: self.enum_base_from_string,
            ModelBase: self.model_base_from_string,
            Attachment: self.attachment_from_string,
            XmlAttribute: self.xmlattribute_from_string,
            ComplexModelBase: self.complex_model_base_from_string
        }

        self._from_string_handlers = cdict(fsh)
        self._from_unicode_handlers = cdict(fsh)

        self._datetime_dsmap = {
            None: self._datetime_from_string,
            'sec': self._datetime_from_sec,
            'sec_float': self._datetime_from_sec_float,
            'msec': self._datetime_from_msec,
            'msec_float': self._datetime_from_msec_float,
            'usec': self._datetime_from_usec,
        }