• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python protocol.ProtocolBase类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中spyne.protocol.ProtocolBase的典型用法代码示例。如果您正苦于以下问题:Python ProtocolBase类的具体用法?Python ProtocolBase怎么用?Python ProtocolBase使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: __init__

    def __init__(self, services, tns, name=None,
                          in_protocol=None, out_protocol=None, interface=None):
        self.services = tuple(services)
        self.tns = tns
        self.name = name

        if self.name is None:
            self.name = self.__class__.__name__.split('.')[-1]

        self.event_manager = EventManager(self)
        self.error_handler = None

        self.interface = Interface(self)
        self.in_protocol = in_protocol
        self.out_protocol = out_protocol

        if self.in_protocol is None:
            from spyne.protocol import ProtocolBase
            self.in_protocol = ProtocolBase(self)
        else:
            self.in_protocol.set_app(self)

        if self.out_protocol is None:
            from spyne.protocol import ProtocolBase
            self.out_protocol = ProtocolBase(self)
        else:
            self.out_protocol.set_app(self)

        register_application(self)

        self.reinitialize()
开发者ID:KetothXupack,项目名称:spyne,代码行数:31,代码来源:application.py


示例2: __init__

    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)
开发者ID:shaung,项目名称:spyne,代码行数:34,代码来源:_base.py


示例3: test_custom_strftime

    def test_custom_strftime(self):
        s = ProtocolBase.strftime(datetime.date(1800, 9, 23),
                                        "%Y has the same days as 1980 and 2008")
        if s != "1800 has the same days as 1980 and 2008":
            raise AssertionError(s)

        print("Testing all day names from 0001/01/01 until 2000/08/01")
        # Get the weekdays.  Can't hard code them; they could be
        # localized.
        days = []
        for i in range(1, 10):
            days.append(datetime.date(2000, 1, i).strftime("%A"))
        nextday = {}
        for i in range(8):
            nextday[days[i]] = days[i + 1]

        startdate = datetime.date(1, 1, 1)
        enddate = datetime.date(2000, 8, 1)
        prevday = ProtocolBase.strftime(startdate, "%A")
        one_day = datetime.timedelta(1)

        testdate = startdate + one_day
        while testdate < enddate:
            if (testdate.day == 1 and testdate.month == 1 and
                                                    (testdate.year % 100 == 0)):
                print("Testing century", testdate.year)
            day = ProtocolBase.strftime(testdate, "%A")
            if nextday[prevday] != day:
                raise AssertionError(str(testdate))
            prevday = day
            testdate = testdate + one_day
开发者ID:ashleysommer,项目名称:spyne,代码行数:31,代码来源:test_primitive.py


示例4: __init__

    def __init__(self, services, tns, name=None,
                          in_protocol=None, out_protocol=None, config=None):
        self.services = tuple(services)
        self.tns = tns
        self.name = name
        self.config = config

        if self.name is None:
            self.name = self.__class__.__name__.split('.')[-1]

        self.event_manager = EventManager(self)
        self.error_handler = None

        self.interface = Interface(self)
        self.in_protocol = in_protocol
        self.out_protocol = out_protocol

        if self.in_protocol is None:
            from spyne.protocol import ProtocolBase
            self.in_protocol = ProtocolBase()
        self.in_protocol.set_app(self)
        # FIXME: this normally is another parameter to set_app but it's kept
        # separate for backwards compatibility reasons.
        self.in_protocol.message = self.in_protocol.REQUEST

        if self.out_protocol is None:
            from spyne.protocol import ProtocolBase
            self.out_protocol = ProtocolBase()
        self.out_protocol.set_app(self)
        # FIXME: this normally is another parameter to set_app but it's kept
        # separate for backwards compatibility reasons.
        self.out_protocol.message = self.out_protocol.RESPONSE

        register_application(self)
开发者ID:1-bit,项目名称:spyne,代码行数:34,代码来源:application.py


示例5: _from_dict_value

    def _from_dict_value(cls, class_, value, validator):
        # validate raw input
        if validator is cls.SOFT_VALIDATION:
            if issubclass(class_, Unicode) and not isinstance(value, basestring):
                raise ValidationError(value)
            if issubclass(class_, Unicode) and not isinstance(value, unicode):
                # Note that String is a subclass of Unicode
                if not (issubclass(class_, String) and isinstance(value, str)):
                    value = ProtocolBase.from_string(class_, value)

            elif issubclass(class_, Decimal) and not isinstance(value,
                                                            (int, long, float)):
                raise ValidationError(value)

            elif issubclass(class_, DateTime) and not (
                                isinstance(value, unicode) and
                                         class_.validate_string(class_, value)):
                raise ValidationError(value)

        # get native type
        if issubclass(class_, ComplexModelBase):
            retval = cls._doc_to_object(class_, value, validator)

        elif issubclass(class_, DateTime):
            retval = ProtocolBase.from_string(class_, value)

        else:
            retval = value

        # validate native type
        if validator is cls.SOFT_VALIDATION and \
                                     not class_.validate_native(class_, retval):
            raise ValidationError(retval)

        return retval
开发者ID:amgibson,项目名称:spyne,代码行数:35,代码来源:dictdoc.py


示例6: test_time

    def test_time(self):
        n = datetime.time(1, 2, 3, 4)

        ret = ProtocolBase.to_string(Time, n)
        self.assertEquals(ret, n.isoformat())

        dt = ProtocolBase.from_string(Time, ret)
        self.assertEquals(n, dt)
开发者ID:amgibson,项目名称:spyne,代码行数:8,代码来源:test_primitive.py


示例7: test_date

    def test_date(self):
        n = datetime.date(2011,12,13)

        ret = ProtocolBase.to_string(Date, n)
        self.assertEquals(ret, n.isoformat())

        dt = ProtocolBase.from_string(Date, ret)
        self.assertEquals(n, dt)
开发者ID:amgibson,项目名称:spyne,代码行数:8,代码来源:test_primitive.py


示例8: test_duration_xml_duration

    def test_duration_xml_duration(self):
        dur = datetime.timedelta(days=5 + 30 + 365, hours=1, minutes=1,
                                                   seconds=12, microseconds=8e5)

        str1 = 'P400DT3672.8S'
        str2 = 'P1Y1M5DT1H1M12.8S'

        self.assertEquals(dur, ProtocolBase.from_string(Duration, str1))
        self.assertEquals(dur, ProtocolBase.from_string(Duration, str2))

        self.assertEquals(dur, ProtocolBase.from_string(Duration, ProtocolBase.to_string(Duration, dur)))
开发者ID:amgibson,项目名称:spyne,代码行数:11,代码来源:test_primitive.py


示例9: set_app

    def set_app(self, value):
        ProtocolBase.set_app(self, value)

        self.validation_schema = None

        if value:
            from spyne.interface.xml_schema import XmlSchema

            xml_schema = XmlSchema(value.interface)
            xml_schema.build_validation_schema()

            self.validation_schema = xml_schema.validation_schema
开发者ID:drowolath,项目名称:spyne,代码行数:12,代码来源:_base.py


示例10: __init__

    def __init__(self, app=None, validator=None, mime_type=None,
            ignore_uncap=False, ignore_wrappers=True, complex_as=dict,
                                                                ordered=False):
        ProtocolBase.__init__(self, app, validator, mime_type, ignore_uncap)

        self.ignore_wrappers = ignore_wrappers
        self.complex_as = complex_as
        self.ordered = ordered
        if ordered:
            raise NotImplementedError('ordered == False')

        self.stringified_types = (DateTime, Date, Time, Uuid, Duration,
                                                                AnyXml, AnyHtml)
开发者ID:dmugtasimov,项目名称:spyne,代码行数:13,代码来源:dictdoc.py


示例11: _to_value

    def _to_value(cls, class_, value, k=None):
        if issubclass(class_, ComplexModelBase):
            return cls._to_dict(class_, value, k)

        if issubclass(class_, DateTime):
            return ProtocolBase.to_string(class_, value)

        if issubclass(class_, Decimal):
            if class_.Attributes.format is None:
                return value
            else:
                return ProtocolBase.to_string(class_, value)

        return value
开发者ID:amgibson,项目名称:spyne,代码行数:14,代码来源:dictdoc.py


示例12: __init__

    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)
开发者ID:specialunderwear,项目名称:spyne,代码行数:49,代码来源:_base.py


示例13: serialize

    def serialize(self, ctx, message):
        assert message in (self.REQUEST, self.RESPONSE)

        self.event_manager.fire_event('before_serialize', ctx)

        if ctx.out_error is not None:
            ctx.out_document = [ProtocolBase.to_dict(ctx.out_error.__class__, ctx.out_error)]

        else:
            # get the result message
            if message is self.REQUEST:
                out_type = ctx.descriptor.in_message
            elif message is self.RESPONSE:
                out_type = ctx.descriptor.out_message
            if out_type is None:
                return

            out_type_info = out_type._type_info

            # instantiate the result message
            out_instance = out_type()

            # assign raw result to its wrapper, result_message
            for i in range(len(out_type_info)):
                attr_name = out_type_info.keys()[i]
                setattr(out_instance, attr_name, ctx.out_object[i])

            ctx.out_document = self._object_to_doc(out_type, out_instance,
                                                    skip_depth=self.skip_depth)

            self.event_manager.fire_event('after_serialize', ctx)
开发者ID:amgibson,项目名称:spyne,代码行数:31,代码来源:dictdoc.py


示例14: test_limits

    def test_limits(self):
        try:
            ProtocolBase.from_string(Integer, "1" * (Integer.__max_str_len__ + 1))
        except:
            pass
        else:
            raise Exception("must fail.")

        ProtocolBase.from_string(UnsignedInteger, "-1") # This is not supposed to fail.

        try:
            UnsignedInteger.validate_native(-1) # This is supposed to fail.
        except:
            pass
        else:
            raise Exception("must fail.")
开发者ID:amgibson,项目名称:spyne,代码行数:16,代码来源:test_primitive.py


示例15: __init__

    def __init__(self, app=None, validator=None):
        """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.
        """

        ProtocolBase.__init__(self, app, validator)
开发者ID:KetothXupack,项目名称:spyne,代码行数:20,代码来源:html.py


示例16: __init__

    def __init__(self, app=None, validator=None, 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.
        :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.
        """

        ProtocolBase.__init__(self, app, validator, skip_depth=skip_depth)
开发者ID:drowolath,项目名称:spyne,代码行数:23,代码来源:html.py


示例17: ProtocolBase

from spyne import D, Integer, ModelBase, Date, DateTime, IpAddress, Decimal
from spyne.protocol import ProtocolBase
from spyne.util import six
from spyne.util.cdict import cdict

if six.PY2:
    bytes = str
else:
    unicode = str


_prot = ProtocolBase()


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()),
开发者ID:knoxsp,项目名称:spyne,代码行数:30,代码来源:dynint.py


示例18: ProtocolBase

from datetime import date, datetime

from spyne import D, Integer, ModelBase, Date, DateTime, IpAddress, Decimal
from spyne.protocol import ProtocolBase
from spyne.util import six
from spyne.util.cdict import cdict


if six.PY2:
    bytes = str
else:
    unicode = str


_prot = ProtocolBase()


MAP = cdict({
    ModelBase: cdict({
        object: lambda _: _,
        bytes: lambda _: _.strip(),
        unicode: lambda _: _.strip(),
    }),

    Decimal: cdict({
        D: lambda _: _,
        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()),
    }),
开发者ID:plq,项目名称:spyne,代码行数:30,代码来源:dyninit.py


示例19: Application

class Application(object):
    """The Application class is the glue between one or more service
    definitions, input and output protocols.

    :param services:     An iterable of ServiceBase subclasses that defines
                         the exposed services.
    :param tns:          The targetNamespace attribute of the exposed
                         service.
    :param name:         The optional name attribute of the exposed service.
                         The default is the name of the application class
                         which is by default 'Application'.
    :param in_protocol:  A ProtocolBase instance that denotes the input
                         protocol. It's only optional for NullServer transport.
    :param out_protocol: A ProtocolBase instance that denotes the output
                         protocol. It's only optional for NullServer transport.
    :param config:       An arbitrary python object to store random global data.

    Supported events:
        * ``method_call``:
            Called right before the service method is executed

        * ``method_return_object``:
            Called right after the service method is executed

        * ``method_exception_object``:
            Called when an exception occurred in a service method, before the
            exception is serialized.

        * ``method_context_created``:
            Called from the constructor of the MethodContext instance.

        * ``method_context_closed``:
            Called from the ``close()`` function of the MethodContext instance,
            which in turn is called by the transport when the response is fully
            sent to the client (or in the client case, the response is fully
            received from server).
    """

    transport = None

    def __init__(self, services, tns, name=None,
                          in_protocol=None, out_protocol=None, config=None):
        self.services = tuple(services)
        self.tns = tns
        self.name = name
        self.config = config

        if self.name is None:
            self.name = self.__class__.__name__.split('.')[-1]

        self.event_manager = EventManager(self)
        self.error_handler = None

        self.interface = Interface(self)
        self.in_protocol = in_protocol
        self.out_protocol = out_protocol

        if self.in_protocol is None:
            from spyne.protocol import ProtocolBase
            self.in_protocol = ProtocolBase()
        self.in_protocol.set_app(self)
        # FIXME: this normally is another parameter to set_app but it's kept
        # separate for backwards compatibility reasons.
        self.in_protocol.message = self.in_protocol.REQUEST

        if self.out_protocol is None:
            from spyne.protocol import ProtocolBase
            self.out_protocol = ProtocolBase()
        self.out_protocol.set_app(self)
        # FIXME: this normally is another parameter to set_app but it's kept
        # separate for backwards compatibility reasons.
        self.out_protocol.message = self.out_protocol.RESPONSE

        register_application(self)

    def process_request(self, ctx):
        """Takes a MethodContext instance. Returns the response to the request
        as a native python object. If the function throws an exception, it
        returns None and sets the exception object to ctx.out_error.

        Overriding this method would break event management. So this is not
        meant to be overridden unless you know what you're doing.
        """

        try:
            # fire events
            self.event_manager.fire_event('method_call', ctx)
            if ctx.service_class is not None:
                ctx.service_class.event_manager.fire_event('method_call', ctx)

            # in object is always a sequence of incoming values. We need to fix
            # that for bare mode.
            if ctx.descriptor.body_style is BODY_STYLE_BARE:
                ctx.in_object = [ctx.in_object]
            elif ctx.descriptor.body_style is BODY_STYLE_EMPTY:
                ctx.in_object = []

            # call user method
            ctx.out_object = self.call_wrapper(ctx)

#.........这里部分代码省略.........
开发者ID:1-bit,项目名称:spyne,代码行数:101,代码来源:application.py


示例20: Application

class Application(object):
    """The Application class is the glue between one or more service
    definitions, input and output protocols.

    :param services:     An iterable of ServiceBase subclasses that defines
                         the exposed services.
    :param tns:          The targetNamespace attribute of the exposed
                         service.
    :param name:         The optional name attribute of the exposed service.
                         The default is the name of the application class
                         which is by default 'Application'.
    :param in_protocol:  A ProtocolBase instance that denotes the input
                         protocol. It's only optional for NullServer transport.
    :param out_protocol: A ProtocolBase instance that denotes the output
                         protocol. It's only optional for NullServer transport.
    :param interface:    Ignored. Kept for backwards-compatibility purposes.

    Supported events:
        * ``method_call``:
            Called right before the service method is executed

        * ``method_return_object``:
            Called right after the service method is executed

        * ``method_exception_object``:
            Called when an exception occurred in a service method, before the
            exception is serialized.

        * ``method_context_created``:
            Called from the constructor of the MethodContext instance.

        * ``method_context_closed``:
            Called from the ``close()`` function of the MethodContext instance,
            which in turn is called by the transport when the response is fully
            sent to the client (or in the client case, the response is fully
            received from server).
    """

    transport = None

    def __init__(self, services, tns, name=None,
                          in_protocol=None, out_protocol=None, interface=None):
        self.services = tuple(services)
        self.tns = tns
        self.name = name

        if self.name is None:
            self.name = self.__class__.__name__.split('.')[-1]

        self.event_manager = EventManager(self)
        self.error_handler = None

        self.interface = Interface(self)
        self.in_protocol = in_protocol
        self.out_protocol = out_protocol

        if self.in_protocol is None:
            from spyne.protocol import ProtocolBase
            self.in_protocol = ProtocolBase()
        self.in_protocol.set_app(self)
        # FIXME: this normally is another parameter to set_app but it's kept
        # separate for backwards compatibility reasons.
        self.in_protocol.message = self.in_protocol.REQUEST

        if self.out_protocol is None:
            from spyne.protocol import ProtocolBase
            self.out_protocol = ProtocolBase()
        self.out_protocol.set_app(self)
        # FIXME: this normally is another parameter to set_app but it's kept
        # separate for backwards compatibility reasons.
        self.out_protocol.message = self.out_protocol.RESPONSE

        register_application(self)

        self.reinitialize()

    def process_request(self, ctx):
        """Takes a MethodContext instance. Returns the response to the request
        as a native python object. If the function throws an exception, it
        returns None and sets the exception object to ctx.out_error.

        Overriding this method would break event management. So this is not
        meant to be overridden unless you know what you're doing.
        """

        try:
            # fire events
            self.event_manager.fire_event('method_call', ctx)
            if ctx.service_class is not None:
                ctx.service_class.event_manager.fire_event('method_call', ctx)

            # call the method
            ctx.out_object = self.call_wrapper(ctx)

            # out object is always an iterable of return values. see
            # MethodContext docstrings for more info
            if ctx.descriptor.body_style is not BODY_STYLE_WRAPPED or \
                                len(ctx.descriptor.out_message._type_info) <= 1:
                # the return value should already be wrapped by a sequence.
                ctx.out_object = [ctx.out_object]
#.........这里部分代码省略.........
开发者ID:buldi,项目名称:spyne,代码行数:101,代码来源:application.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python xml.XmlDocument类代码示例发布时间:2022-05-27
下一篇:
Python primitive.NATIVE_MAP类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap