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 )
def __init__(self): Fault.__init__(self, faultcode="Documented", faultstring="A documented fault", faultactor='http://faultactor.example.com', detail=etree.Element('something') )
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.' )
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 and len(header_envelope[0]) > 0: header = header_envelope[0].getchildren() body=None if len(body_envelope) > 0 and len(body_envelope[0]) > 0: body = body_envelope[0].getchildren()[0] return header, body
def __init__(self, err): # TODO: handle that err could be a list of strings, first element # should be faultstring, rest should go in self.extra. faultstring = err if isinstance(err, Exception) and err.args: faultstring = err.args[0] self.extra = err.args[1:] faultstring = str(faultstring) Fault.__init__(self, faultcode=self.faultcode, faultstring=faultstring)
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')")
def get(file_path): '''This method loads a document from the specified file path and returns it. If the path isn't found, an exception is raised. ''' if file_path is None: raise Fault("Client", "file_path is mandatory") if not os.path.exists(file_path): raise Fault("Client.FileName", "File '%s' not found" % file_path) document = open(file_path, 'rb').read() # the service automatically loads the data from the file. # alternatively, The data could be manually loaded into memory # and loaded into the Attachment like: # document = Attachment(data=data_from_file) return [document]
def test_to_parent_element_w_detail(self): from lxml.etree import Element element = Element('testing') detail = Element('something') fault = Fault(detail=detail) cls = Fault XmlObject().to_parent_element(cls, fault, 'urn:ignored', element) (child,) = element.getchildren() self.failUnless(child.find('detail').find('something') is detail)
def _parse_xml_string(xml_string, charset=None): if charset: string = ''.join([s.decode(charset) for s in xml_string]) else: string = ''.join(xml_string) try: try: root, xmlids = etree.XMLID(string) except XMLSyntaxError, e: logger.error(string) raise Fault('Client.XMLSyntaxError', str(e)) except ValueError, e: logger.debug('%r -- falling back to str decoding.' % (e)) try: root, xmlids = etree.XMLID(string.encode(charset)) except XMLSyntaxError, e: logger.error(string) raise Fault('Client.XMLSyntaxError', str(e))
def test_to_parent_element_wo_detail(self): from lxml.etree import Element import rpclib.const.xml_ns ns_soap_env = rpclib.const.xml_ns.soap_env element = Element('testing') fault = Fault() cls = Fault XmlObject().to_parent_element(cls, fault, 'urn:ignored', element) (child,) = element.getchildren() self.assertEqual(child.tag, '{%s}Fault' % ns_soap_env) self.assertEqual(child.find('faultcode').text, 'senv:Server') self.assertEqual(child.find('faultstring').text, 'Fault') self.assertEqual(child.find('faultactor').text, '') self.failIf(child.findall('detail'))
def put(ctx, content): '''This method accepts an Attachment object, and returns the filename of the archived file. ''' if content is None: raise Fault("Client.BadRequest") fd, fname = mkstemp() os.close(fd) f = open(fname, 'wb') for chunk in content: f.write(chunk) f.close() return fname
def rootPage(self, *args, **kwargs): """Handle an incoming SOAP request or a non-SOAP WSDL query.""" self.response.content_type = 'text/xml' if not self.request._request.body: return self.service_description() if True: ctx = MethodContext() in_string = collapse_swa(self.request.content_type, self.request._request.body) in_obj = self.get_in_object(ctx, in_string, self.request._request.charset) out_obj = self.get_out_object(ctx, in_obj) out_string = self.get_out_string(ctx, out_obj) return out_string else: #except Exception, e: if getattr(self, 'debug_soap', False): raise self.response.status = '500 Internal Server Error' fault = Fault(faultstring=str(e)) resp = etree.tostring(fault, encoding=string_encoding) return resp
def __init__(self, faultstring): Fault.__init__(self, 'Client.ValidationError', 'The string %r could not be validated.' % faultstring)
def __init__(self, faultstring): Fault.__init__(self, 'Client.ResourceNotFound', faultstring)
def __init__(self, faultstring): Fault.__init__(self, 'Client.ArgumentError', faultstring)
def test_ctor_faultcode_w_senv_prefix(self): fault = Fault(faultcode='Other') self.assertEqual(fault.faultcode, 'Other') self.assertEqual(repr(fault), "Fault(Other: 'Fault')")
class Application(object): '''This class is the glue between one or more service definitions, interface and protocol choices. :param services: An iterable of ServiceBase subclasses that define the exposed services. :param tns: The targetNamespace attribute of the exposed service. :param interface: An InterfaceBase instance that sets the service definition document standard. :param in_protocol: A ProtocolBase instance that defines the input protocol. :param out_protocol: A ProtocolBase instance that defines the output protocol. :param name: The optional name attribute of the exposed service. The default is the name of the application class which is, by default, 'Application'. 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_constructed Called from the constructor of the MethodContext instance. * method_context_destroyed Called from the destructor of the MethodContext instance. ''' transport = None def __init__(self, services, tns, interface, in_protocol, out_protocol, name=None, supports_fanout_methods=False): self.services = services self.tns = tns self.name = name self.supports_fanout_methods = supports_fanout_methods if self.name is None: self.name = self.__class__.__name__.split('.')[-1] self.in_protocol = in_protocol self.in_protocol.set_app(self) self.out_protocol = out_protocol self.out_protocol.set_app(self) self.interface = interface self.interface.set_app(self) self.__public_methods = {} self.__classes = {} self.event_manager = EventManager(self) self.error_handler = None 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) 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 len(ctx.descriptor.out_message._type_info) == 0: ctx.out_object = [None] elif len(ctx.descriptor.out_message._type_info) == 1: ctx.out_object = [ctx.out_object] # otherwise, the return value should already be wrapped in an # iterable. # fire events self.event_manager.fire_event('method_return_object', ctx) ctx.service_class.event_manager.fire_event( 'method_return_object', ctx) except Fault, e: logger.exception(e) ctx.out_error = e # fire events self.event_manager.fire_event('method_exception_object', ctx) if ctx.service_class != None: ctx.service_class.event_manager.fire_event( 'method_exception_object', ctx) except Exception, e: logger.exception(e) ctx.out_error = Fault('Server', str(e)) # fire events self.event_manager.fire_event('method_exception_object', ctx) if ctx.service_class != None: ctx.service_class.event_manager.fire_event( 'method_exception_object', ctx)
def soap_exception(): raise Fault("Plausible", "A plausible fault", 'http://faultactor.example.com', detail=etree.Element('something'))
def __init__(self, faultstring): Fault.__init__(self, "Client.SchemaValidationError", faultstring)
def __init__(self, faultstring=""): Fault.__init__(self, 'Client.RequestNotAllowed', faultstring)
def __init__(self, faultstring): Fault.__init__(self, 'Client.RequestTooLong', faultstring)
def __init__(self, value): Fault.__init__(self, faultcode='Client.KeyError', faultstring='Value %r not found' % value )
def __init__(self, faultstring="Requested resource not found"): Fault.__init__(self, 'Client.ResourceNotFound', faultstring)
class HttpRpc(ProtocolBase): """The so-called REST-minus-the-verbs HttpRpc protocol implementation. It only works with the http server (wsgi) transport. It only parses requests where the whole data is in the 'QUERY_STRING', i.e. the part after '?' character in a URI string. """ def set_validator(self, validator): if validator == 'soft' or validator is self.SOFT_VALIDATION: self.validator = self.SOFT_VALIDATION elif validator is None: self.validator = None else: raise ValueError(validator) def create_in_document(self, ctx, in_string_encoding=None): assert ctx.transport.type == 'wsgi', ("This protocol only works with " "the wsgi api.") ctx.in_document = ctx.transport.req_env def decompose_incoming_envelope(self, ctx): ctx.method_request_string = '{%s}%s' % (self.app.interface.get_tns(), ctx.in_document['PATH_INFO'].split('/')[-1]) logger.debug("\033[92mMethod name: %r\033[0m" % ctx.method_request_string) ctx.in_header_doc = _get_http_headers(ctx.in_document) ctx.in_body_doc = parse_qs(ctx.in_document['QUERY_STRING']) logger.debug('\theader : %r' % (ctx.in_header_doc)) logger.debug('\tbody : %r' % (ctx.in_body_doc)) def dict_to_object(self, doc, inst_class): simple_type_info = inst_class.get_simple_type_info(inst_class) inst = inst_class.get_deserialization_instance() # this is for validating cls.Attributes.{min,max}_occurs frequencies = {} for k, v in doc.items(): member = simple_type_info.get(k, None) if member is None: logger.debug("discarding field %r" % k) continue mo = member.type.Attributes.max_occurs value = getattr(inst, k, None) if value is None: value = [] elif mo == 1: raise Fault('Client.ValidationError', '"%s" member must occur at most %d times' % (k, max_o)) for v2 in v: if (self.validator is self.SOFT_VALIDATION and not member.type.validate_string(member.type, v2)): raise ValidationError(v2) native_v2 = member.type.from_string(v2) if (self.validator is self.SOFT_VALIDATION and not member.type.validate_native(member.type, native_v2)): raise ValidationError(v2) value.append(native_v2) # set frequencies of parents. if not (member.path[:-1] in frequencies): for i in range(1,len(member.path)): logger.debug("\tset freq %r = 1" % (member.path[:i],)) frequencies[member.path[:i]] = 1 freq = frequencies.get(member.path, 0) freq += 1 frequencies[member.path] = freq logger.debug("\tset freq %r = %d" % (member.path, freq)) if mo == 1: value = value[0] cinst = inst ctype_info = inst_class.get_flat_type_info(inst_class) pkey = member.path[0] for i in range(len(member.path) - 1): pkey = member.path[i] if not (ctype_info[pkey].Attributes.max_occurs in (0,1)): raise Exception("HttpRpc deserializer does not support " "non-primitives with max_occurs > 1") ninst = getattr(cinst, pkey, None) if ninst is None: ninst = ctype_info[pkey].get_deserialization_instance() setattr(cinst, pkey, ninst) cinst = ninst ctype_info = ctype_info[pkey]._type_info if isinstance(cinst, list): cinst.extend(value) logger.debug("\tset array %r(%r) = %r" % (member.path, pkey, value)) else: setattr(cinst, member.path[-1], value) logger.debug("\tset default %r(%r) = %r" % (member.path, pkey, value)) try: print inst.qo.vehicles except Exception,e: print e if self.validator is self.SOFT_VALIDATION: sti = simple_type_info.values() sti.sort(key=lambda x: (len(x.path), x.path)) pfrag = None for s in sti: if len(s.path) > 1 and pfrag != s.path[:-1]: pfrag = s.path[:-1] ctype_info = inst_class.get_flat_type_info(inst_class) for i in range(len(pfrag)): f = pfrag[i] ntype_info = ctype_info[f] min_o = ctype_info[f].Attributes.min_occurs max_o = ctype_info[f].Attributes.max_occurs val = frequencies.get(pfrag[:i+1], 0) if val < min_o: raise Fault('Client.ValidationError', '"%s" member must occur at least %d times' % ('_'.join(pfrag[:i+1]), min_o)) if max_o != 'unbounded' and val > max_o: raise Fault('Client.ValidationError', '"%s" member must occur at most %d times' % ('_'.join(pfrag[:i+1]), max_o)) ctype_info = ntype_info.get_flat_type_info(ntype_info) val = frequencies.get(s.path, 0) min_o = s.type.Attributes.min_occurs max_o = s.type.Attributes.max_occurs if val < min_o: raise Fault('Client.ValidationError', '"%s" member must occur at least %d times' % ('_'.join(s.path), min_o)) if max_o != 'unbounded' and val > max_o: raise Fault('Client.ValidationError', '"%s" member must occur at most %d times' % ('_'.join(s.path), max_o)) return inst
def __init__(self): Fault.__init__(self, faultcode="Documented", faultstring="A documented fault", faultactor='http://faultactor.example.com', detail=etree.Element('something'))
def dict_to_object(self, doc, inst_class): simple_type_info = inst_class.get_simple_type_info(inst_class) inst = inst_class.get_deserialization_instance() # this is for validating cls.Attributes.{min,max}_occurs frequencies = {} for k, v in doc.items(): member = simple_type_info.get(k, None) if member is None: logger.debug("discarding field %r" % k) continue mo = member.type.Attributes.max_occurs value = getattr(inst, k, None) if value is None: value = [] elif mo == 1: raise Fault('Client.ValidationError', '"%s" member must occur at most %d times' % (k, max_o)) for v2 in v: if (self.validator is self.SOFT_VALIDATION and not member.type.validate_string(member.type, v2)): raise ValidationError(v2) native_v2 = member.type.from_string(v2) if (self.validator is self.SOFT_VALIDATION and not member.type.validate_native(member.type, native_v2)): raise ValidationError(v2) value.append(native_v2) # set frequencies of parents. if not (member.path[:-1] in frequencies): for i in range(1,len(member.path)): logger.debug("\tset freq %r = 1" % (member.path[:i],)) frequencies[member.path[:i]] = 1 freq = frequencies.get(member.path, 0) freq += 1 frequencies[member.path] = freq logger.debug("\tset freq %r = %d" % (member.path, freq)) if mo == 1: value = value[0] cinst = inst ctype_info = inst_class.get_flat_type_info(inst_class) pkey = member.path[0] for i in range(len(member.path) - 1): pkey = member.path[i] if not (ctype_info[pkey].Attributes.max_occurs in (0,1)): raise Exception("HttpRpc deserializer does not support " "non-primitives with max_occurs > 1") ninst = getattr(cinst, pkey, None) if ninst is None: ninst = ctype_info[pkey].get_deserialization_instance() setattr(cinst, pkey, ninst) cinst = ninst ctype_info = ctype_info[pkey]._type_info if isinstance(cinst, list): cinst.extend(value) logger.debug("\tset array %r(%r) = %r" % (member.path, pkey, value)) else: setattr(cinst, member.path[-1], value) logger.debug("\tset default %r(%r) = %r" % (member.path, pkey, value)) try: print inst.qo.vehicles except Exception,e: print e
def __init__(self, faultstring): Fault.__init__(self, 'Client.SchemaValidationError', faultstring)
def __init__(self): Fault.__init__(self, faultcode='Client.UnauthenticatedError', faultstring='This resource can only be accessed after authentication.' )
def test_ctor_explicit_faultstring(self): fault = Fault(faultstring='Testing') self.assertEqual(fault.faultstring, 'Testing') self.assertEqual(repr(fault), "Fault(Server: 'Testing')")