コード例 #1
0
ファイル: django.py プロジェクト: simudream/spyne
 def __init__(self, validation_error_exc):
     """Construct fault with code Client.<validation_error_type_name>."""
     message = str(validation_error_exc)
     # we do not want to reuse initialization of BaseValidationError
     Fault.__init__(
         self, faultcode='Client.{0}'.format(
             type(validation_error_exc).__name__), faultstring=message)
コード例 #2
0
ファイル: django.py プロジェクト: simudream/spyne
 def __init__(self, does_not_exist_exc):
     """Construct fault with code Client.<object_name>NotFound."""
     message = str(does_not_exist_exc)
     object_name = message.split()[0]
     # we do not want to reuse initialization of ResourceNotFoundError
     Fault.__init__(
         self, faultcode='Client.{0}NotFound'.format(object_name),
         faultstring=message)
コード例 #3
0
    def call_wrapper(self, ctx):
        try:

            log.info("Received request: %s", ctx.function)

            start = datetime.datetime.now()
            res = ctx.service_class.call_wrapper(ctx)
            log.info("Call took: %s" % (datetime.datetime.now() - start))
            return res
        except HydraError as e:
            log.critical(e)
            rollback_transaction()
            traceback.print_exc(file=sys.stdout)
            code = "HydraError %s" % e.code
            raise HydraServiceError(e.message, code)
        except ObjectNotFoundError as e:
            log.critical(e)
            rollback_transaction()
            raise
        except Fault as e:
            log.critical(e)
            rollback_transaction()
            raise
        except Exception as e:
            log.critical(e)
            traceback.print_exc(file=sys.stdout)
            rollback_transaction()
            raise Fault('Server', e.message)
コード例 #4
0
def complex_from_element(prot, cls, element):
    inst = cls.get_deserialization_instance()

    flat_type_info = cls.get_flat_type_info(cls)

    # this is for validating cls.Attributes.{min,max}_occurs
    frequencies = defaultdict(int)

    # parse input to set incoming data to related attributes.
    for c in element:
        key = c.tag.split('}')[-1]
        frequencies[key] += 1

        member = flat_type_info.get(key, None)
        if member is None:
            continue

        mo = member.Attributes.max_occurs
        if mo > 1:
            value = getattr(inst, key, None)
            if value is None:
                value = []

            value.append(prot.from_element(member, c))

        else:
            value = prot.from_element(member, c)

        setattr(inst, key, value)

        for key in c.attrib:
            member = flat_type_info.get(key, None)
            if member is None or (not issubclass(member, XmlAttribute)) or \
                                                     member.attribute_of == key:
                continue

            value = prot.from_string(member.type, c.attrib[key])

            setattr(inst, key, value)

    for key in element.attrib:
        member = flat_type_info.get(key, None)
        if member is None:
            continue

        value = prot.from_string(member.type, element.attrib[key])

        setattr(inst, key, value)

    if prot.validator is prot.SOFT_VALIDATION:
        for key, c in flat_type_info.items():
            val = frequencies.get(key, 0)
            if (val < c.Attributes.min_occurs
                    or val > c.Attributes.max_occurs):
                raise Fault(
                    'Client.ValidationError',
                    '%r member does not respect frequency constraints.' % key)

    return inst
コード例 #5
0
ファイル: primitive.py プロジェクト: mangroovie/spyne
    def from_string(cls, string):
        if cls.Attributes.max_str_len is not None and \
                                 len(str(string)) > cls.Attributes.max_str_len:
            raise Fault(
                'Client.ValidationError', 'String longer than '
                '%d characters.' % cls.Attributes.max_str_len)

        try:
            return int(string)
        except ValueError:
            try:
                return int(string)
            except ValueError:
                raise ValidationError(string)
コード例 #6
0
ファイル: xml.py プロジェクト: FutureMind/spyne
    def deserialize(self, ctx, message):
        """Takes a MethodContext instance and a string containing ONE root xml
        tag.

        Returns the corresponding native python object.

        Not meant to be overridden.
        """

        assert message in (self.REQUEST, self.RESPONSE)

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

        if ctx.descriptor is None:
            if ctx.in_error is None:
                raise Fault("Client",
                            "Method %r not found." % ctx.method_request_string)
            else:
                raise ctx.in_error

        if message is self.REQUEST:
            body_class = ctx.descriptor.in_message
        elif message is self.RESPONSE:
            body_class = ctx.descriptor.out_message

        # decode method arguments
        if ctx.in_body_doc is None:
            ctx.in_object = [None] * len(body_class._type_info)
        else:
            ctx.in_object = self.from_element(ctx, body_class, ctx.in_body_doc)

        if logger.level == logging.DEBUG and message is self.REQUEST:
            line_header = '%sRequest%s' % (LIGHT_GREEN, END_COLOR)

            outdoc_str = None
            if ctx.out_document is not None:
                outdoc_str = etree.tostring(
                    ctx.out_document,
                    xml_declaration=self.xml_declaration,
                    pretty_print=True)

            logger.debug("%s %s" % (line_header, outdoc_str))

        self.event_manager.fire_event('after_deserialize', ctx)
コード例 #7
0
ファイル: xml.py プロジェクト: cdcanasg/spyne
    def create_in_document(self, ctx, charset=None):
        """Uses the iterable of string fragments in ``ctx.in_string`` to set
        ``ctx.in_document``."""

        string = b''.join(ctx.in_string)
        try:
            try:
                ctx.in_document = etree.fromstring(string,
                                        parser=XMLParser(**self.parser_kwargs))

            except ValueError:
                logger.debug('ValueError: Deserializing from unicode strings '
                             'with encoding declaration is not supported by '
                             'lxml.')
                ctx.in_document = etree.fromstring(string.decode(charset),
                                                                    self.parser)
        except XMLSyntaxError as e:
            logger_invalid.error("%r in string %r", e, string)
            raise Fault('Client.XMLSyntaxError', str(e))
コード例 #8
0
def _on_method_call(ctx):

    env = ctx.transport.req_env

    if ctx.function == AuthenticationService.login:
        return

    if ctx.in_object is None:
        raise ArgumentError("RequestHeader is null")

    if ctx.in_header is None:
        raise AuthenticationError("No headers!")

    session = env['beaker.session']

    if session.get('user_id') is None:
        raise Fault("No Session!")

    ctx.in_header.user_id = session['user_id']
    ctx.in_header.username = session['username']
コード例 #9
0
ファイル: xml.py プロジェクト: cdcanasg/spyne
    def complex_from_element(self, ctx, cls, elt):
        inst = cls.get_deserialization_instance(ctx)

        flat_type_info = cls.get_flat_type_info(cls)

        # this is for validating cls.Attributes.{min,max}_occurs
        frequencies = defaultdict(int)
        cls_attrs = self.get_cls_attrs(cls)

        if cls_attrs._xml_tag_body_as is not None:
            for xtba_key, xtba_type in cls_attrs._xml_tag_body_as:
                xtba_attrs = self.get_cls_attrs(xtba_type.type)
                if issubclass(xtba_type.type, (ByteArray, File)):
                    value = self.from_unicode(xtba_type.type, elt.text,
                                                        self.binary_encoding)
                else:
                    value = self.from_unicode(xtba_type.type, elt.text)

                inst._safe_set(xtba_key, value, xtba_type.type, xtba_attrs)

        # parse input to set incoming data to related attributes.
        for c in elt:
            if isinstance(c, etree._Comment):
                continue

            key = c.tag.split('}', 1)[-1]
            frequencies[key] += 1

            member = flat_type_info.get(key, None)
            if member is None:
                member, key = cls._type_info_alt.get(key, (None, key))
                if member is None:
                    member, key = cls._type_info_alt.get(c.tag, (None, key))
                    if member is None:
                        continue

            member_attrs = self.get_cls_attrs(member)
            mo = member_attrs.max_occurs
            if mo > 1:
                value = getattr(inst, key, None)
                if value is None:
                    value = []

                value.append(self.from_element(ctx, member, c))

            else:
                value = self.from_element(ctx, member, c)

            inst._safe_set(key, value, member, member_attrs)

            for key, value_str in c.attrib.items():
                submember = flat_type_info.get(key, None)

                if submember is None:
                    submember, key = cls._type_info_alt.get(key, (None, key))
                    if submember is None:
                        continue

                submember_attrs = self.get_cls_attrs(submember)
                mo = submember_attrs.max_occurs
                if mo > 1:
                    value = getattr(inst, key, None)
                    if value is None:
                        value = []

                    value.append(self.from_unicode(submember.type, value_str))

                else:
                    value = self.from_unicode(submember.type, value_str)

                inst._safe_set(key, value, submember.type, submember_attrs)

        for key, value_str in elt.attrib.items():
            member = flat_type_info.get(key, None)
            if member is None:
                member, key = cls._type_info_alt.get(key, (None, key))
                if member is None:
                    continue

            if not issubclass(member, XmlAttribute):
                continue

            if issubclass(member.type, (ByteArray, File)):
                value = self.from_unicode(member.type, value_str,
                                                           self.binary_encoding)
            else:
                value = self.from_unicode(member.type, value_str)

            member_attrs = self.get_cls_attrs(member.type)
            inst._safe_set(key, value, member.type, member_attrs)

        if self.validator is self.SOFT_VALIDATION:
            for key, c in flat_type_info.items():
                val = frequencies.get(key, 0)
                attr = self.get_cls_attrs(c)
                if val < attr.min_occurs or val > attr.max_occurs:
                    raise Fault('Client.ValidationError', '%r member does not '
                                         'respect frequency constraints.' % key)

        return inst
コード例 #10
0
ファイル: application.py プロジェクト: albatros-tan/spyne
    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:
            ctx.fire_event('method_call')

            # 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)

            # out object is always a sequence 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:
                # if it's not a wrapped method, OR there's just one return type
                # we wrap it ourselves
                ctx.out_object = [ctx.out_object]

            # Now that the processing is switched to the outgoing message,
            # point ctx.protocol to ctx.out_protocol
            ctx.protocol = ctx.outprot_ctx

            ctx.fire_event('method_return_object')

        except Redirect as e:
            try:
                e.do_redirect()

                ctx.out_object = [None]

                # Now that the processing is switched to the outgoing message,
                # point ctx.protocol to ctx.out_protocol
                ctx.protocol = ctx.outprot_ctx

                ctx.fire_event('method_redirect')

            except Exception as e:
                logger_server.exception(e)
                ctx.out_error = Fault('Server',
                                      get_fault_string_from_exception(e))

                ctx.fire_event('method_redirect_exception')

        except Fault as e:
            if e.faultcode == 'Client' or e.faultcode.startswith('Client.'):
                logger_client.exception(e)
            else:
                logger.exception(e)

            ctx.out_error = e

            ctx.fire_event('method_exception_object')

        # we don't catch BaseException because we actually don't want to catch
        # "system-exiting" exceptions. See:
        # https://docs.python.org/2/library/exceptions.html#exceptions.Exception
        except Exception as e:
            logger_server.critical(e, **{'exc_info': 1})

            ctx.out_error = Fault('Server', get_fault_string_from_exception(e))

            ctx.fire_event('method_exception_object')
コード例 #11
0
ファイル: model.py プロジェクト: harshil07/spyne
def complex_from_element(prot, cls, element):
    inst = cls.get_deserialization_instance()

    flat_type_info = cls.get_flat_type_info(cls)

    # this is for validating cls.Attributes.{min,max}_occurs
    frequencies = defaultdict(int)

    xtba_key, xtba_type = cls.Attributes._xml_tag_body_as
    if xtba_key is not None:
        if issubclass(xtba_type.type, (ByteArray, File)):
            value = prot.from_string(xtba_type.type, element.text,
                                     prot.default_binary_encoding)
        else:
            value = prot.from_string(xtba_type.type, element.text)
        setattr(inst, xtba_key, value)

    # parse input to set incoming data to related attributes.
    for c in element:
        key = c.tag.split('}')[-1]
        frequencies[key] += 1

        member = flat_type_info.get(key, None)
        if member is None:
            member, key = cls._type_info_alt.get(key, (None, key))
            if member is None:
                member, key = cls._type_info_alt.get(c.tag, (None, key))
                if member is None:
                    continue

        mo = member.Attributes.max_occurs
        if mo > 1:
            value = getattr(inst, key, None)
            if value is None:
                value = []

            value.append(prot.from_element(member, c))

        else:
            value = prot.from_element(member, c)

        setattr(inst, key, value)

        for key, value_str in c.attrib.items():
            member = flat_type_info.get(key, None)
            if member is None:
                member, key = cls._type_info_alt.get(key, (None, key))
                if member is None:
                    continue

            if (not issubclass(member, XmlAttribute)) or \
                                                     member.attribute_of == key:
                continue

            if mo > 1:
                value = getattr(inst, key, None)
                if value is None:
                    value = []

                value.append(prot.from_string(member.type, value_str))

            else:
                value = prot.from_string(member.type, value_str)

            setattr(inst, key, value)

    for key, value_str in element.attrib.items():
        member = flat_type_info.get(key, None)
        if member is None:
            member, key = cls._type_info_alt.get(key, (None, key))
            if member is None:
                continue

        if (not issubclass(member,
                           XmlAttribute)) or member.attribute_of == key:
            continue

        if issubclass(member.type, (ByteArray, File)):
            value = prot.from_string(member.type, value_str,
                                     prot.default_binary_encoding)
        else:
            value = prot.from_string(member.type, value_str)

        setattr(inst, key, value)

    if prot.validator is prot.SOFT_VALIDATION:
        for key, c in flat_type_info.items():
            val = frequencies.get(key, 0)
            if (val < c.Attributes.min_occurs
                    or val > c.Attributes.max_occurs):
                raise Fault(
                    'Client.ValidationError',
                    '%r member does not respect frequency constraints.' % key)

    return inst
コード例 #12
0
    def __init__(self, message, code="HydraError"):

        Fault.__init__(self,
                faultcode=code,
                faultstring=message
        )
コード例 #13
0
    def __init__(self):

        Fault.__init__(self,
                faultcode='Client.AuthorizationError',
                faultstring='You are not authozied to access this resource.'
            )
コード例 #14
0
 def __init__(self, user_name):
     Fault.__init__(self,
             faultcode='Client.AuthenticationError',
             faultstring='Invalid authentication request for %r' % user_name
         )
コード例 #15
0
    def __init__(self, message):

        Fault.__init__(self,
                faultcode='NoObjectFoundError',
                faultstring=message
        )