def __init__(self, username):
        # TODO: self.transport.http.resp_code = HTTP_401

        Fault.__init__(
            self,
            faultcode='Client.LoginUnsupported',
            faultstring='Login Unsupported for non free user  %r' % username)
示例#2
0
def _from_soap(in_envelope_xml, xmlids=None, **kwargs):
    """Parses the xml string into the header and payload.
    """
    ns_soap = kwargs.pop('ns', ns.NS_SOAP11_ENV)

    if xmlids:
        resolve_hrefs(in_envelope_xml, xmlids)

    if in_envelope_xml.tag != '{%s}Envelope' % ns_soap:
        raise Fault('Client.SoapError',
                    'No {%s}Envelope element was found!' % ns_soap)

    header_envelope = in_envelope_xml.xpath('e:Header',
                                            namespaces={'e': ns_soap})
    body_envelope = in_envelope_xml.xpath('e:Body', namespaces={'e': ns_soap})

    if len(header_envelope) == 0 and len(body_envelope) == 0:
        raise Fault('Client.SoapError', 'Soap envelope is empty!')

    header = None
    if len(header_envelope) > 0:
        header = header_envelope[0].getchildren()

    body = None
    if len(body_envelope) > 0 and len(body_envelope[0]) > 0:
        body = body_envelope[0][0]

    return header, body
示例#3
0
文件: msgpack.py 项目: skumyol/spyne
    def deserialize(self, ctx, message):
        assert message in (self.REQUEST, self.RESPONSE)

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

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

        # instantiate the result message
        if message is self.REQUEST:
            body_class = ctx.descriptor.in_message
        elif message is self.RESPONSE:
            body_class = ctx.descriptor.out_message
        else:
            raise Exception("what?")

        if ctx.in_error:
            ctx.in_error = Fault(**ctx.in_error)

        elif body_class:
            ctx.in_object = self._doc_to_object(body_class, ctx.in_body_doc,
                                                self.validator)

        else:
            ctx.in_object = []

        self.event_manager.fire_event('after_deserialize', ctx)
示例#4
0
 def update_whois_info(id, wInfo):
     for entry in EntryContainer.entries:
         if entry.id == id:
             for contact in wInfo.contacts:
                 if contactparser.contact_exists(contact.id):
                     res, status = contactparser.edit_contact(
                         contact.id, contact)
                     if status != 200:
                         raise Fault(
                             faultcode="Server",
                             faultstring=
                             "Internal error when updating contacts!")
                 else:
                     res, status = contactparser.add_contact(contact)
                     if status != 201:
                         raise Fault(faultcode="Server",
                                     faultstring=
                                     "Internal error when adding contacts!")
             entry.id = wInfo.id
             entry.website = wInfo.website
             entry.ipaddress = wInfo.ipaddress
             entry.contacts = wInfo.contacts
             return wInfo
     raise Fault(faultcode="Client",
                 faultstring="Could not find entry with given id!")
示例#5
0
    def __init__(self, obj, custom_msg='The value %r could not be validated.'):
        s = repr(obj)

        if len(s) > MAX_STRING_FIELD_LENGTH:
            s = s[:MAX_STRING_FIELD_LENGTH] + "(...)"

        Fault.__init__(self, 'Client.ValidationError', custom_msg % s)
示例#6
0
文件: server_soap.py 项目: 66ru/spyne
    def __init__(self):
        # TODO: self.transport.http.resp_code = HTTP_401

        Fault.__init__(self,
                faultcode='Client.AuthorizationError',
                faultstring='You are not authorized to access this resource.'
            )
示例#7
0
 def changeMovieSoap(Id, Title, Genre, Release_date, Rating, Album_ID):
     try:
         r = requests.get('http://web1:81/albums/' + Album_ID)
         if r.status_code == 200 and re.search('^[0-9]?$', Id):
             movies[int(Id)]['Title'] = Title
             movies[int(Id)]['Genre'] = Genre
             movies[int(Id)]['Rating'] = Rating
             movies[int(Id)]['Release_date'] = Release_date
             movies[int(Id)]['Album_ID'] = Album_ID
             movie = movies[int(Id)]
         else:
             raise Fault(faultcode='Client',
                         faultstring='',
                         faultactor='',
                         detail={
                             'Message':
                             'Error. Service Albums status is not 200.'
                         })
         return Movie(ID=movie["ID"],
                      Title=movie["Title"],
                      Genre=movie["Genre"],
                      Rating=movie["Rating"],
                      Release_date=movie["Release_date"],
                      Album_ID=movie["Album_ID"])
     except:
         raise Fault(
             faultcode='Client',
             faultstring='',
             faultactor='',
             detail={'Message': 'Error. Service Albums is not available.'})
示例#8
0
    def __init__(self, user_name):
        # TODO: self.transport.http.resp_code = HTTP_401

        Fault.__init__(self,
                faultcode='Client.AuthenticationError',
                faultstring='Invalid authentication request for %r' % user_name
            )
示例#9
0
 def __init__(self):
     Fault.__init__(
         self,
         faultcode="Documented",
         faultstring="A documented fault",
         faultactor='http://faultactor.example.com',
     )
示例#10
0
文件: server_soap.py 项目: 66ru/spyne
    def __init__(self, user_name):
        # TODO: self.transport.http.resp_code = HTTP_401

        Fault.__init__(self,
                faultcode='Client.AuthenticationError',
                faultstring='Invalid authentication request for %r' % user_name
            )
示例#11
0
    def __init__(self):
        # TODO: self.transport.http.resp_code = HTTP_401

        Fault.__init__(self,
                faultcode='Client.AuthorizationError',
                faultstring='You are not authorized to access this resource.'
            )
示例#12
0
文件: error.py 项目: amgibson/spyne
    def __init__(self, obj, custom_msg='The value %r could not be validated.'):
        s = repr(obj)

        if len(s) > MAX_STRING_FIELD_LENGTH:
            s = s[:MAX_STRING_FIELD_LENGTH] + "(...)"

        Fault.__init__(self, 'Client.ValidationError', custom_msg % s)
示例#13
0
文件: soap11.py 项目: mfkaptan/spyne
def _from_soap(in_envelope_xml, xmlids=None):
    '''Parses the xml string into the header and payload.'''

    if xmlids:
        resolve_hrefs(in_envelope_xml, xmlids)

    if in_envelope_xml.tag != '{%s}Envelope' % ns.soap_env:
        raise Fault('Client.SoapError',
                    'No {%s}Envelope element was found!' % ns.soap_env)

    header_envelope = in_envelope_xml.xpath('e:Header',
                                            namespaces={'e': ns.soap_env})
    body_envelope = in_envelope_xml.xpath('e:Body',
                                          namespaces={'e': ns.soap_env})

    if len(header_envelope) == 0 and len(body_envelope) == 0:
        raise Fault('Client.SoapError',
                    'Soap envelope is empty!' % ns.soap_env)

    header = None
    if len(header_envelope) > 0:
        header = header_envelope[0].getchildren()

    body = None
    if len(body_envelope) > 0 and len(body_envelope[0]) > 0:
        body = body_envelope[0][0]

    return header, body
示例#14
0
文件: _service.py 项目: 66ru/spyne
 def __init__(self):
     Fault.__init__(self,
             faultcode="Documented",
             faultstring="A documented fault",
             faultactor='http://faultactor.example.com',
             detail=etree.Element('something')
         )
示例#15
0
 def change_password(ctx, UserName, Password):
     token = ctx.in_header.Token
     user_name = ctx.in_header.UserName
     if all([user_name, token]):
         result = handlers.change_password(UserName, Password, token)
         if result['result']:
             return result['message']
         raise Fault(result['side'], result['message'])
     raise Fault('Client', 'Нет прав доступа.')
示例#16
0
 def set_stock_price(ctx, StockName, Price):
     user_name = ctx.in_header.UserName
     token = ctx.in_header.Token
     if all([user_name, token]):
         result = handlers.set_stock_price(user_name, token, StockName, Price)
         if result['result']:
             return result['message']
         raise Fault(result['side'], result['message'])
     raise Fault('Client', 'Нет прав доступа.')
示例#17
0
 def find_infraction(self, id):
     try:
         infraction = Infraction.objects.get(pk=id)
         return infraction
     except IntegrityError as e:
         raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1])
     except Infraction.DoesNotExist:
         raise Fault(faultcode='404',
                     faultstring=str('Infraction not exist'))
示例#18
0
 def get_whois_info(id):
     if id == None:
         raise Fault(faultcode="Client", faultstring="'id' field is empty")
     for entry in EntryContainer.entries:
         if entry.id == id:
             entry.updateContactList()
             return entry
     raise Fault(faultcode="Client",
                 faultstring="Entry not found with given id!")
示例#19
0
 def find_municipality(self, id):
     try:
         municipality = Municipality.objects.get(pk=id)
         return municipality
     except IntegrityError as e:
         raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1])
     except Municipality.DoesNotExist:
         raise Fault(faultcode='404',
                     faultstring=str('Municipality not exist'))
示例#20
0
    def _handle_rpc_body(self, p_ctx) -> typing.Optional[Fault]:
        """
        Do the heavy lifting of the request handling here. This can be run in a thread.
        """
        self.get_in_object(p_ctx)
        if p_ctx.in_error:
            logger.error(p_ctx.in_error)
            return p_ctx.in_error

        self.get_out_object(p_ctx)
        if p_ctx.out_error:
            logger.error(p_ctx.out_error)
            return p_ctx.out_error

        try:
            self.get_out_string(p_ctx)
        except Exception as e:
            p_ctx.out_error = Fault("Server",
                                    get_fault_string_from_exception(e))
            logger.exception(p_ctx.out_error, exc_info=e)
            return p_ctx.out_error

        have_protocol_headers = (isinstance(p_ctx.out_protocol, HttpRpc)
                                 and p_ctx.out_header_doc is not None)
        if have_protocol_headers:
            p_ctx.transport.resp_headers.update(p_ctx.out_header_doc)

        return None
示例#21
0
文件: django.py 项目: harshil07/spyne
    def handle_rpc(self, request, *args, **kwargs):
        """Handle rpc request.

        :params request: Django HttpRequest instance.
        :returns: HttpResponse instance.

        """
        contexts = self.get_contexts(request)
        p_ctx, others = contexts[0], contexts[1:]

        if p_ctx.in_error:
            return self.handle_error(p_ctx, others, p_ctx.in_error)

        self.get_in_object(p_ctx)
        if p_ctx.in_error:
            logger.error(p_ctx.in_error)
            return self.handle_error(p_ctx, others, p_ctx.in_error)

        self.get_out_object(p_ctx)
        if p_ctx.out_error:
            return self.handle_error(p_ctx, others, p_ctx.out_error)

        try:
            self.get_out_string(p_ctx)

        except Exception, e:
            logger.exception(e)
            p_ctx.out_error = Fault('Server',
                                    get_fault_string_from_exception(e))
            return self.handle_error(p_ctx, others, p_ctx.out_error)
示例#22
0
    def decompose_incoming_envelope(self, ctx, message):
        """Sets ``ctx.in_body_doc``, ``ctx.in_header_doc`` and
        ``ctx.method_request_string`` using ``ctx.in_document``.
        """

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

        # set ctx.in_header
        ctx.transport.in_header_doc = None  # use an rpc protocol if you want headers.

        doc = ctx.in_document

        ctx.in_header_doc = None
        ctx.in_body_doc = doc

        if len(doc) == 0:
            raise Fault("Client", "Empty request")

        logger.debug('\theader : %r' % (ctx.in_header_doc))
        logger.debug('\tbody   : %r' % (ctx.in_body_doc))

        if not isinstance(doc, dict) or len(doc) != 1:
            raise ValidationError("Need a dictionary with exactly one key "
                                  "as method name.")

        mrs, = doc.keys()
        ctx.method_request_string = '{%s}%s' % (self.app.interface.get_tns(),
                                                mrs)
示例#23
0
def _parse_xml_string(xml_string, parser, charset=None):
    xml_string = iter(xml_string)
    chunk = next(xml_string)
    if isinstance(chunk, six.binary_type):
        string = b''.join(chain((chunk, ), xml_string))
    else:
        string = ''.join(chain((chunk, ), xml_string))

    if charset:
        string = string.decode(charset)

    try:
        try:
            root, xmlids = etree.XMLID(string, parser)

        except ValueError as e:
            logger.debug('ValueError: Deserializing from unicode strings with '
                         'encoding declaration is not supported by lxml.')
            root, xmlids = etree.XMLID(string.encode(charset), parser)

    except XMLSyntaxError as e:
        logger_invalid.error("%r in string %r", e, string)
        raise Fault('Client.XMLSyntaxError', str(e))

    return root, xmlids
示例#24
0
 def delete_whois_info(id):
     for entry in EntryContainer.entries:
         if entry.id == id:
             EntryContainer.entries.remove(entry)
             return "Item deleted!"
     raise Fault(faultcode="Client",
                 faultstring="Entry not found with given id!")
示例#25
0
 def add_infraction(self, infraction):
     data = infraction.as_dict()
     try:
         inf = Infraction.objects.create(**data)
         sendmailnotification = Sendmail()
         sendmailnotification.send_mail(
             mail_list=[data['offender_mail']],
             subject='Multa de Transito - Simit Services',
             template='infraction_mail',
             offender_name=str(inf.offender_name),
             infraction_id=str(inf.id),
             date=str(inf.date),
             location=str(inf.location))
         return Infraction.objects.filter(id=inf.id).values(
             'id', 'date', 'road_type', 'road_name', 'municipality',
             'location', 'plate', 'infraction_code', 'vehicle_type',
             'vehicle_service', 'offender_type', 'offender_document_type',
             'offender_document_id', 'offender_name', 'offender_license_id',
             'offender_address', 'offender_age', 'offender_phone',
             'offender_mail', 'owner_document_type', 'owner_document_id',
             'owner_name', 'company_id', 'company_name',
             'transit_agent_name', 'transit_agent_entity',
             'transit_agent_id', 'transit_agent_observations',
             'document_url', 'state', 'state_date').first()
     except IntegrityError as e:
         raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1])
示例#26
0
    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 = [Fault.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),

            self.event_manager.fire_event('after_serialize', ctx)
示例#27
0
 def add_infraction(self, infraction):
     data = infraction.as_dict()
     try:
         inf = Infraction.objects.create(**data)
         sendmailnotification = SendMailNotifications()
         sendmailnotification.send_mail(
             list_emails=[data['offender_mail']],
             subject='Multa de Transito - Simit Services',
             content_xml='<h2>Multa de Transito N0: ' + str(inf.id) +
             '</h2></br><p>' +
             'Estimado Infractor se ha creado una nueva Multa de Transito asociado al ciudadano '
             + str(inf.offender_document_id) + ' - ' +
             str(inf.offender_name) +
             '</p></br><p>Realice el pago lo mas pronto posible para evitar sanciones</p>'
             + '<br><h3>SIMIT Services</h3>')
         return Infraction.objects.filter(id=inf.id).values(
             'id', 'date', 'road_type', 'road_name', 'municipality',
             'location', 'plate', 'infraction_code', 'vehicle_type',
             'vehicle_service', 'offender_type', 'offender_document_type',
             'offender_document_id', 'offender_name', 'offender_license_id',
             'offender_address', 'offender_age', 'offender_phone',
             'offender_mail', 'owner_document_type', 'owner_document_id',
             'owner_name', 'company_id', 'company_name',
             'transit_agent_name', 'transit_agent_entity',
             'transit_agent_id', 'transit_agent_observations',
             'document_url', 'state', 'state_date').first()
     except IntegrityError as e:
         raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1])
示例#28
0
    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 = [
                Fault.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),

            self.event_manager.fire_event('after_serialize', ctx)
示例#29
0
 def test_ctor_defaults(self):
     fault = Fault()
     self.assertEqual(fault.faultcode, 'Server')
     self.assertEqual(fault.faultstring, 'Fault')
     self.assertEqual(fault.faultactor, '')
     self.assertEqual(fault.detail, None)
     self.assertEqual(repr(fault), "Fault(Server: 'Fault')")
示例#30
0
 def addTicketToEvent(MovieName, NumberOfTickets):
     try:
         if (len(MovieName) == 0):
             raise Fault(faultcode='Client',
                         faultstring='',
                         faultactor='',
                         detail={
                             'Message':
                             'Error. Title not provided or is invalid'
                         })
         if (NumberOfTickets < 1):
             raise Fault(
                 faultcode='Client',
                 faultstring='',
                 faultactor='',
                 detail={'Error. TicNumber not provided or is invalid'})
         requestData = {'title': MovieName}
         r = requests.get('http://service:81/movies', params=requestData)
         eventID = r.json()
         for i in range(0, NumberOfTickets):
             lastId = int(ticketsDB[len(ticketsDB) - 1]['ID']) + 1
             ticket = {
                 'ID': str(lastId),
                 'Barcode': '',
                 'EID': eventID[0]['ID'],
                 'Current_Zone': '0',
                 'Rated': '0'
             }
             ticketsDB.append(ticket)
         eventTickets = [
             tic for tic in ticketsDB
             if (tic['EID'] == str(eventID[0]['ID']))
         ]
         m = []
         for ticket in eventTickets:
             m.append(
                 Ticket(ID=ticket["ID"],
                        Barcode=ticket["Barcode"],
                        EID=ticket["EID"],
                        Current_Zone=ticket["Current_Zone"],
                        Rated=ticket["Rated"]))
         return m
     except requests.RequestException as e:
         raise Fault(faultcode='503',
                     faultstring='',
                     faultactor='',
                     detail={'Message': str(e)})
示例#31
0
    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]

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

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

        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

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

        except Exception as e:
            logger.exception(e)

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

            # fire events
            self.event_manager.fire_event('method_exception_object', ctx)
            if ctx.service_class is not None:
                ctx.service_class.event_manager.fire_event(
                    'method_exception_object', ctx)
示例#32
0
 def edit_municipality(self, municipality):
     data = municipality.as_dict()
     try:
         Municipality.objects.filter(id=data['id']).update(**data)
         return Municipality.objects.filter(id=data['id']).values(
             'id', 'dian_code', 'name').first()
     except IntegrityError as e:
         raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1])
示例#33
0
def _eb_deferred(ret, request, p_ctx, others, resource):
    app = p_ctx.app

    # DRY this with what's in Application.process_request
    if issubclass(ret.type, Redirect):
        try:
            ret.value.do_redirect()

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

            _cb_deferred(None, request, p_ctx, others, resource, cb=False)

            # fire events
            app.event_manager.fire_event('method_redirect', p_ctx)
            if p_ctx.service_class is not None:
                p_ctx.service_class.event_manager.fire_event(
                    'method_redirect', p_ctx)

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

            # fire events
            app.event_manager.fire_event('method_redirect_exception', p_ctx)
            if p_ctx.service_class is not None:
                p_ctx.service_class.event_manager.fire_event(
                    'method_redirect_exception', p_ctx)

    elif issubclass(ret.type, Fault):
        p_ctx.out_error = ret.value

        ret = resource.handle_rpc_error(p_ctx, others, p_ctx.out_error,
                                        request)

        # fire events
        app.event_manager.fire_event('method_exception_object', p_ctx)
        if p_ctx.service_class is not None:
            p_ctx.service_class.event_manager.fire_event(
                'method_exception_object', p_ctx)

        request.write(ret)

    else:
        p_ctx.out_error = ret.value
        ret.printTraceback()
        p_ctx.out_error = InternalError(ret.value)

        # fire events
        app.event_manager.fire_event('method_exception_object', p_ctx)
        if p_ctx.service_class is not None:
            p_ctx.service_class.event_manager.fire_event(
                'method_exception_object', p_ctx)

    request.finish()
示例#34
0
 def Login(ctx, _this, userName, password):
     self = ctx.udc
     if (userName == 'root' and password == 'Embe1mpls') or \
        (userName == 'u' and password == 'p') or \
        (userName == 'user' and password == 'pass'):
         self.auth = serializers.AuthResponse()
         self.auth.key = self.login_id
         return self.auth.serialize()
     raise Fault('Client.Authentication', 'Authorization failed')
示例#35
0
 def changeMovieAlbumSoap(Id, Title, Genre, Release_date, Rating, Album,
                          AlbumGenre, Producer, Artist):
     if Artist != '':
         try:
             for i in range(0, len(movies)):
                 if movies[i]["ID"] == Id:
                     r = requests.put('http://web1:81/albums/' +
                                      movies[i]["Album_ID"],
                                      json={
                                          "Album": Album,
                                          "Artist": Artist,
                                          "Genre": AlbumGenre,
                                          "Producer": Producer
                                      })
                     if r.status_code == 200 and re.search('^[0-9]?$', Id):
                         movies[i]['Title'] = Title
                         movies[i]['Genre'] = Genre
                         movies[i]['Rating'] = Rating
                         movies[i]['Release_date'] = Release_date
                         movie = movies[i]
                     else:
                         raise Fault(
                             faultcode='Client',
                             faultstring='',
                             faultactor='',
                             detail={
                                 'Message':
                                 'Error. Service Albums status is not 200.'
                             })
             return Movie(ID=movie["ID"],
                          Title=movie["Title"],
                          Genre=movie["Genre"],
                          Rating=movie["Rating"],
                          Release_date=movie["Release_date"],
                          Album_ID=movie["Album_ID"])
         except:
             raise Fault(faultcode='Client',
                         faultstring='',
                         faultactor='',
                         detail={
                             'Message':
                             'Error. Service Albums is not available.'
                         })
示例#36
0
    def test_to_parent_w_detail(self):
        from lxml.etree import Element
        element = Element('testing')
        detail = Element('something')
        fault = Fault(detail=detail)
        cls = Fault

        XmlDocument().to_parent(None, cls, fault, element, 'urn:ignored')

        (child,) = element.getchildren()
        self.assertTrue(child.find('detail').find('something') is detail)
示例#37
0
    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 = [
                [MessagePackRpc.MSGPACK_RESPONSE, 0,
                           Fault.to_dict(ctx.out_error.__class__, ctx.out_error)]
            ]
            return

        # get the result message
        if message is self.REQUEST:
            out_type = ctx.descriptor.in_message
            msgtype = MessagePackRpc.MSGPACK_REQUEST
            method_name_or_error = ctx.descriptor.operation_name

        elif message is self.RESPONSE:
            out_type = ctx.descriptor.out_message
            msgtype = MessagePackRpc.MSGPACK_RESPONSE
            method_name_or_error = None

        else:
            raise Exception("what?")

        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, (k, v) in enumerate(out_type_info.items()):
            attr_name = k
            out_instance._safe_set(attr_name, ctx.out_object[i], v)

        # transform the results into a dict:
        if out_type.Attributes.max_occurs > 1:
            params = (self._to_dict_value(out_type, inst, set())
                                                       for inst in out_instance)
        else:
            params = self._to_dict_value(out_type, out_instance, set())

        ctx.out_document = [[msgtype, 0, method_name_or_error, params]]

        self.event_manager.fire_event('after_serialize', ctx)
示例#38
0
文件: msgpack.py 项目: buldi/spyne
    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 = [MessagePackRpc.MSGPACK_RESPONSE, 0,
                         Fault.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])

            # transform the results into a dict:
            if out_type.Attributes.max_occurs > 1:
                ctx.out_document = [[MessagePackRpc.MSGPACK_RESPONSE, 0, None,
                        (self._to_value(out_type, inst)
                                                      for inst in out_instance)
                    ]]
            else:
                ctx.out_document = [[MessagePackRpc.MSGPACK_RESPONSE, 0, None,
                                        self._to_value(out_type, out_instance),
                                   ]]

            self.event_manager.fire_event('after_serialize', ctx)
    def __init__(self, reason, username, device_id):
        # TODO: self.transport.http.resp_code = HTTP_401
        if reason == "badLogin":

            Fault.__init__(
                self,
                faultcode='Client.LoginInvalid',
                faultstring="Username or Password Fail for %r'" % username)
        elif reason == "freeUser":

            details = {'SonosError': "666", }
            Fault.__init__(
                self,
                faultcode='Client.LoginUnsupported',
                faultstring='%r is not a premium account.' % username,
                detail=details)
        elif reason == "unsupportedTerritory":

            Fault.__init__(
                self,
                faultcode="Client.UnsupportedTerritory",
                faultstring='%r is not in a supported territory.' % username)
示例#40
0
文件: server_soap.py 项目: 66ru/spyne
 def __init__(self, value):
     Fault.__init__(self,
             faultcode='Client.KeyError',
             faultstring='Value %r not found' % value
         )
示例#41
0
 def __init__(self, fault_object,
          fault_string="You do not have permission to access this resource"):
     Fault.__init__(self, 'Client.InvalidCredentialsError', fault_string)
示例#42
0
文件: error.py 项目: amgibson/spyne
 def __init__(self, faultstring=""):
     Fault.__init__(self, 'Client.ArgumentError', faultstring)
示例#43
0
文件: faults.py 项目: Linutronix/elbe
 def __init__(self, err):
     Fault.__init__(
         self,
         faultcode="ElbeProjectError",
         faultstring=str(err))
示例#44
0
文件: error.py 项目: amgibson/spyne
 def __init__(self, faultstring=""):
     Fault.__init__(self, 'Client.RequestTooLong', faultstring)
示例#45
0
文件: error.py 项目: amgibson/spyne
 def __init__(self, faultstring=""):
     Fault.__init__(self, 'Client.RequestNotAllowed', faultstring)
示例#46
0
文件: faults.py 项目: Linutronix/elbe
 def __init__(self):
     Fault.__init__(
         self,
         faultcode="ElbeAuthenticationFailed",
         faultstring="Authentication Failed")
示例#47
0
文件: error.py 项目: amgibson/spyne
 def __init__(self, faultstring="Requested resource not found"):
     Fault.__init__(self, 'Client.ResourceNotFound', faultstring)
示例#48
0
文件: json.py 项目: harshil07/spyne
    def serialize(self, ctx, message):
        assert message in (self.REQUEST, self.RESPONSE)

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

        # construct the soap response, and serialize it
        nsmap = self.app.interface.nsmap
        ctx.out_document = {
            "ver": self.version,
        }
        if ctx.out_error is not None:
            ctx.out_document[self.FAULT] = Fault.to_dict(Fault, ctx.out_error)

        else:
            if message is self.REQUEST:
                header_message_class = ctx.descriptor.in_header
                body_message_class = ctx.descriptor.in_message

            elif message is self.RESPONSE:
                header_message_class = ctx.descriptor.out_header
                body_message_class = ctx.descriptor.out_message

            # assign raw result to its wrapper, result_message
            out_type_info = body_message_class._type_info
            out_object = body_message_class()

            keys = iter(out_type_info)
            values = iter(ctx.out_object)
            while True:
                try:
                    k = keys.next()
                except StopIteration:
                    break
                try:
                    v = values.next()
                except StopIteration:
                    v = None

                setattr(out_object, k, v)

            ctx.out_document[self.BODY] = ctx.out_body_doc = \
                            self._object_to_doc(body_message_class, out_object)

            # header
            if ctx.out_header is not None and header_message_class is not None:
                if isinstance(ctx.out_header, (list, tuple)):
                    out_headers = ctx.out_header
                else:
                    out_headers = (ctx.out_header,)

                ctx.out_header_doc = out_header_doc = []

                for header_class, out_header in zip(header_message_class,
                                                                   out_headers):
                    out_header_doc.append(self._object_to_doc(header_class,
                                                                    out_header))

                if len(out_header_doc) > 1:
                    ctx.out_document[self.HEAD] = out_header_doc
                else:
                    ctx.out_document[self.HEAD] = out_header_doc[0]

        self.event_manager.fire_event('after_serialize', ctx)
示例#49
0
文件: faults.py 项目: Linutronix/elbe
 def __init__(self):
     Fault.__init__(self, faultcode="ElbeInvalidState",
                    faultstring="Project is Busy ! Operation Invalid")
示例#50
0
文件: server_soap.py 项目: 66ru/spyne
 def __init__(self):
     Fault.__init__(self,
             faultcode='Client.UnauthenticatedError',
             faultstring='This resource can only be accessed after authentication.'
         )
示例#51
0
文件: faults.py 项目: Linutronix/elbe
 def __init__(self):
     Fault.__init__(
         self,
         faultcode="ElbeNotLoggedIn",
         faultstring="Not authenticated ! "
                     "Cant let you perform this command.")
示例#52
0
文件: faults.py 项目: Linutronix/elbe
 def __init__(self, exc):
     Fault.__init__(
         self,
         faultcode="ElbeValidationError",
         faultstring=exc.__repr__())
示例#53
0
文件: faults.py 项目: Linutronix/elbe
 def __init__(self):
     Fault.__init__(
         self,
         faultcode="ElbeNotAuthorized",
         faultstring="Not Authorized ! Cant let you perform this command.")
示例#54
0
 def __init__(self, fault_object,
                             fault_string="Requested resource %r not found"):
     Fault.__init__(self, 'Client.ResourceNotFound',
                                                 fault_string % fault_object)
示例#55
0
 def __init__(self, faultstring="", data=""):
     Fault.__init__(self, 'Client.InvalidInput', repr((faultstring, data)))
示例#56
0
 def __init__(self, error):
     Fault.__init__(self, 'Server', "InternalError: An unknown error has occured.")
示例#57
0
文件: _base.py 项目: drowolath/spyne
 def __init__(self, faultstring):
     Fault.__init__(self, 'Client.SchemaValidationError', faultstring)
示例#58
0
文件: error.py 项目: 66ru/spyne
 def __init__(self, faultstring):
     Fault.__init__(self, 'Client.ValidationError',
                     'The value %r could not be validated.' % faultstring)
示例#59
0
文件: __init__.py 项目: shaung/spyne
 def __init__(self, data=None):
     Fault.__init__(self, "Client.MessagePackDecodeError", data)
示例#60
0
文件: _service.py 项目: shaung/spyne
 def __init__(self):
     Fault.__init__(self,
             faultcode="Documented",
             faultstring="A documented fault",
             faultactor='http://faultactor.example.com',
         )