def to_xml(cls, value, name='SOAP-ENV:Fault'): fault = ElementTree.Element(name) ElementTree.SubElement(fault, 'faultcode').text = value.faultcode ElementTree.SubElement(fault, 'faultstring').text = value.faultstring detail = ElementTree.SubElement(fault, 'detail').text = value.detail return fault
def _add_messages_for_methods(self, root, methods): ''' A private method for adding message elements to the wsdl @param the the root element of the wsdl @param the list of methods. ''' messages = [] #make messages for method in methods: methodName = method.name # making in part inMessage = ElementTree.Element('message') inMessage.set('name',method.inMessage.typ) if len(method.inMessage.params) > 0: inPart = ElementTree.SubElement(inMessage,'part') inPart.set('name',method.inMessage.name) inPart.set('element','tns:'+method.inMessage.typ) messages.append(inMessage) # making out part outMessage = ElementTree.Element('message') outMessage.set('name',method.outMessage.typ) if len(method.outMessage.params) > 0: outPart = ElementTree.SubElement(outMessage,'part') outPart.set('name', method.outMessage.name) outPart.set('element', 'tns:'+method.outMessage.typ) messages.append(outMessage) for message in messages: root.append(message)
def make_soap_envelope(message, tns=None, header_elements=None): ''' This method takes the results from a soap method call, and wraps them in the appropriate soap envelope with any specified headers @param the message of the soap envelope, either an element or list of elements @param any header elements to be included in the soap response @returns the envelope element ''' envelope = ElementTree.Element('SOAP-ENV:Envelope') if tns: envelope.set('xmlns:tns',tns) envelope.set('xmlns',tns) envelope.set('xmlns:SOAP-ENV','http://schemas.xmlsoap.org/soap/envelope/') envelope.set('xmlns:xsi','http://www.w3.org/1999/XMLSchema-instance') envelope.set('xmlns:xs','http://www.w3.org/2001/XMLSchema') if header_elements: headerElement = ElementTree.SubElement(envelope,'SOAP-ENV:Header') for h in header_elements: headerElement.append(h) body = ElementTree.SubElement(envelope,'SOAP-ENV:Body') if type(message) == list: for m in message: body.append(m) elif message != None: body.append(message) return envelope
def to_xml(self, data, name='xsd:retval'): element = ElementTree.Element(name) for k, v in data.items(): item = ElementTree.SubElement(element, '%sItem' % self.get_datatype()) key = ElementTree.SubElement(item, 'key') key.text = k ser = self.serializer if v == None: ser = Null item.append(ser.to_xml(v, 'value')) return element
def _add_schema(self, types, methods): '''A private method for adding the appropriate entries to the schema for the types in the specified methods @param the schema node to add the schema elements to @param the list of methods. ''' schema_entries = {} for method in methods: params = method.inMessage.params returns = method.outMessage.params for name,param in params: param.add_to_schema(schema_entries) if returns: returns[0][1].add_to_schema(schema_entries) method.inMessage.add_to_schema(schema_entries) method.outMessage.add_to_schema(schema_entries) schemaNode = ElementTree.SubElement(types, "schema") schemaNode.set("targetNamespace", self.__tns__) schemaNode.set("xmlns", "http://www.w3.org/2001/XMLSchema") for xxx, node in schema_entries.items(): schemaNode.append(node) return schemaNode
def create_xml_subelement(parent, name): ''' Factory method to create a new XML subelement ''' if not name.startswith("{") and None in parent.nsmap: name = qualify(name, parent.nsmap[None]) return ElementTree.SubElement(parent, name)
def add_to_schema(self,schemaDict): complexType = ElementTree.Element('xs:complexType') complexType.set('name',self.typ) sequence = ElementTree.SubElement(complexType,'xs:sequence') if self.params: for name,serializer in self.params: e = ElementTree.SubElement(sequence,'xs:element') e.set('name',name) e.set('type',serializer.get_datatype(True)) element = ElementTree.Element('xs:element') element.set('name',self.typ) element.set('type','%s:%s'%('tns',self.typ)) schemaDict[self.typ] = complexType schemaDict[self.typ+'Element'] = element
def add_to_schema(cls, schema_dict): complexTypeNode = ElementTree.Element('complexType') complexTypeNode.set('name', cls.get_datatype()) sequenceNode = ElementTree.SubElement(complexTypeNode, 'sequence') faultTypeElem = ElementTree.SubElement(sequenceNode, 'element') faultTypeElem.set('name', 'detail') faultTypeElem.set('type', 'xs:string') faultTypeElem = ElementTree.SubElement(sequenceNode, 'element') faultTypeElem.set('name', 'message') faultTypeElem.set('type', 'xs:string') schema_dict[cls.get_datatype()] = complexTypeNode typeElementItem = ElementTree.Element('element') typeElementItem.set('name', 'ExceptionFaultType') typeElementItem.set('type', cls.get_datatype(True)) schema_dict['%sElement' % (cls.get_datatype(True))] = typeElementItem
def add_to_schema(self, schema_dict): typ = self.get_datatype() self.serializer.add_to_schema(schema_dict) if not schema_dict.has_key(typ): # items itemNode = ElementTree.Element('complexType') itemNode.set('name', '%sItem' % typ) sequence = ElementTree.SubElement(itemNode, 'sequence') key_node = ElementTree.SubElement(sequence, 'element') key_node.set('name', 'key') key_node.set('minOccurs', '1') key_node.set('type', 'xs:string') value_node = ElementTree.SubElement(sequence, 'element') value_node.set('name', 'value') value_node.set('minOccurs', '1') value_node.set('type', self.serializer.get_datatype(True)) complexTypeNode = ElementTree.Element("complexType") complexTypeNode.set('name', typ) sequenceNode = ElementTree.SubElement(complexTypeNode, 'sequence') elementNode = ElementTree.SubElement(sequenceNode, 'element') elementNode.set('minOccurs', '0') elementNode.set('maxOccurs', 'unbounded') elementNode.set('name', '%sItem' % typ) elementNode.set('type', 'tns:%sItem' % typ) schema_dict[self.get_datatype(True)] = complexTypeNode schema_dict['tns:%sItem' % typ] = itemNode typeElement = ElementTree.Element("element") typeElement.set('name', typ) typeElement.set('type', self.get_datatype(True)) schema_dict['%sElement' % (self.get_datatype(True))] = typeElement typeElementItem = ElementTree.Element("element") typeElementItem.set('name', '%sItem' % typ) typeElementItem.set('type', '%sItem' % self.get_datatype(True)) schema_dict['%sElementItem' % (self.get_datatype(True))] = typeElementItem
def create_callback_info_headers(messageId, replyTo): '''Creates MessageId and ReplyTo headers for initiating an async function''' messageIdElement = ElementTree.Element( '{http://schemas.xmlsoap.org/ws/2003/03/addressing}MessageID') messageIdElement.text = messageId replyToElement = ElementTree.Element( '{http://schemas.xmlsoap.org/ws/2003/03/addressing}ReplyTo') addressElement = ElementTree.SubElement( replyToElement, '{http://schemas.xmlsoap.org/ws/2003/03/addressing}Address') addressElement.text = replyTo return messageIdElement, replyToElement
def add_to_schema(cls, schemaDict): if not schemaDict.has_key(cls.get_datatype(True)): for k, v in cls.soap_members.items(): v.add_to_schema(schemaDict) schema_node = ElementTree.Element('xs:complexType') schema_node.set('name', cls.__name__) sequence_node = ElementTree.SubElement(schema_node, 'xs:sequence') for k, v in cls.soap_members.items(): member_node = ElementTree.SubElement(sequence_node, 'xs:element') member_node.set('name', k) member_node.set('minOccurs', '0') member_node.set('type', v.get_datatype(True)) typeElement = ElementTree.Element("xs:element") typeElement.set('name', cls.__name__) typeElement.set('type', 'tns:' + cls.__name__) schemaDict[cls.get_datatype(True) + 'Complex'] = schema_node schemaDict[cls.get_datatype(True)] = typeElement
def add_to_schema(self, schema_dict): typ = self.get_datatype() self.serializer.add_to_schema(schema_dict) if not schema_dict.has_key(typ): complexTypeNode = ElementTree.Element("xs:complexType") complexTypeNode.set('name', self.get_datatype(False)) sequenceNode = ElementTree.SubElement(complexTypeNode, 'xs:sequence') elementNode = ElementTree.SubElement(sequenceNode, 'xs:element') elementNode.set('minOccurs', '0') elementNode.set('maxOccurs', 'unbounded') elementNode.set('type', self.serializer.get_datatype(True)) elementNode.set('name', self.serializer.get_datatype(False)) typeElement = ElementTree.Element("xs:element") typeElement.set('name', typ) typeElement.set('type', self.get_datatype(True)) schema_dict['%sElement' % (self.get_datatype(True))] = typeElement schema_dict[self.get_datatype(True)] = complexTypeNode
def make_soap_fault(faultString, faultCode='Server', detail=None): ''' This method populates a soap fault message with the provided fault string and details. @param faultString the short description of the error @param detail the details of the exception, such as a stack trace @param faultCode defaults to 'Server', but can be overridden @returns the element corresponding to the fault message ''' envelope = ElementTree.Element('SOAP-ENV:Envelope') envelope.set('xmlns:SOAP-ENV','http://schemas.xmlsoap.org/soap/envelope/') body = ElementTree.SubElement(envelope,'SOAP-ENV:Body') f = Fault(faultCode,faultString,detail) body.append(Fault.to_xml(f)) return envelope
def _add_bindings_for_methods(self, root, serviceName, methods): ''' A private method for adding bindings to the wsdld @param the root element of the wsdl @param the name of this service @param the methods to be add to the binding node ''' hasCallbacks = self._hasCallbacks() # make binding binding = ElementTree.SubElement(root,'binding') binding.set('name',serviceName) binding.set('type','tns:%s'%serviceName) sbinding = ElementTree.SubElement(binding,'soap:binding') sbinding.set('style','document') sbinding.set('transport','http://schemas.xmlsoap.org/soap/http') if hasCallbacks: callbackBinding = ElementTree.SubElement(root,'binding') callbackBinding.set('name','%sCallback'%serviceName) callbackBinding.set('type','typens:%sCallback'%serviceName) sbinding = ElementTree.SubElement(callbackBinding,'soap:binding') sbinding.set('transport','http://schemas.xmlsoap.org/soap/http') for method in methods: operation = ElementTree.Element('operation') operation.set('name',method.name) soapOperation = ElementTree.SubElement(operation,'soap:operation') soapOperation.set('soapAction',method.soapAction) soapOperation.set('style','document') input = ElementTree.SubElement(operation,'input') input.set('name',method.inMessage.typ) soapBody = ElementTree.SubElement(input,'soap:body') soapBody.set('use','literal') if method.outMessage.params != None and not method.isAsync and not method.isCallback: output = ElementTree.SubElement(operation,'output') output.set('name',method.outMessage.typ) soapBody = ElementTree.SubElement(output,'soap:body') soapBody.set('use','literal') if method.isCallback: relatesTo = ElementTree.SubElement(input,'soap:header') relatesTo.set('message','tns:RelatesToHeader') relatesTo.set('part','RelatesTo') relatesTo.set('use','literal') callbackBinding.append(operation) else: if method.isAsync: rtHeader = ElementTree.SubElement(input,'soap:header') rtHeader.set('message','tns:ReplyToHeader') rtHeader.set('part','ReplyTo') rtHeader.set('use','literal') midHeader = ElementTree.SubElement(input,'soap:header') midHeader.set('message','tns:MessageIDHeader') midHeader.set('part','MessageID') midHeader.set('use','literal') binding.append(operation)
def wsdl(self, url): ''' This method generates and caches the wsdl for this object based on the soap methods designated by the soapmethod or soapdocument descriptors @param url the url that this service can be found at. This must be passed in by the caller because this object has no notion of the server environment in which it runs. @returns the string of the wsdl ''' if not self.__wsdl__ == None: # return the cached __wsdl__ return self.__wsdl__ url = url.replace('.wsdl','') # otherwise build it serviceName = self.__class__.__name__.split('.')[-1] tns = self.__tns__ root = ElementTree.Element("definitions") root.set('targetNamespace',tns) root.set('xmlns:tns',tns) root.set('xmlns:typens',tns) root.set('xmlns','http://schemas.xmlsoap.org/wsdl/') root.set('xmlns:soap','http://schemas.xmlsoap.org/wsdl/soap/') root.set('xmlns:xs','http://www.w3.org/2001/XMLSchema') root.set('xmlns:plnk','http://schemas.xmlsoap.org/ws/2003/05/partner-link/') root.set('xmlns:SOAP-ENC',"http://schemas.xmlsoap.org/soap/encoding/") root.set('xmlns:wsdl',"http://schemas.xmlsoap.org/wsdl/") root.set('name',serviceName) types = ElementTree.SubElement(root,"types") methods = self.methods() hasCallbacks = self._hasCallbacks() self._add_schema(types,methods) self._add_messages_for_methods(root,methods) # add necessary async headers # WS-Addressing -> RelatesTo ReplyTo MessageID # callback porttype if hasCallbacks: root.set('xmlns:wsa','http://schemas.xmlsoap.org/ws/2003/03/addressing') wsaSchemaNode = ElementTree.SubElement(types, "schema") wsaSchemaNode.set("targetNamespace", tns+'Callback') wsaSchemaNode.set("xmlns", "http://www.w3.org/2001/XMLSchema") importNode = ElementTree.SubElement(wsaSchemaNode, "import") importNode.set("namespace", "http://schemas.xmlsoap.org/ws/2003/03/addressing") importNode.set("schemaLocation", "http://schemas.xmlsoap.org/ws/2003/03/addressing/") reltMessage = ElementTree.SubElement(root,'message') reltMessage.set('name','RelatesToHeader') reltPart = ElementTree.SubElement(reltMessage,'part') reltPart.set('name','RelatesTo') reltPart.set('element','wsa:RelatesTo') replyMessage = ElementTree.SubElement(root,'message') replyMessage.set('name','ReplyToHeader') replyPart = ElementTree.SubElement(replyMessage,'part') replyPart.set('name','ReplyTo') replyPart.set('element','wsa:ReplyTo') idHeader = ElementTree.SubElement(root,'message') idHeader.set('name','MessageIDHeader') idPart = ElementTree.SubElement(idHeader,'part') idPart.set('name','MessageID') idPart.set('element','wsa:MessageID') # make portTypes callbackPortType = ElementTree.SubElement(root,'portType') callbackPortType.set('name','%sCallback'%serviceName) cbServiceName = '%sCallback'%serviceName cbService = ElementTree.SubElement(root,'service') cbService.set('name',cbServiceName) cbWsdlPort = ElementTree.SubElement(cbService,'port') cbWsdlPort.set('name',cbServiceName) cbWsdlPort.set('binding','tns:%s'%cbServiceName) cbAddr = ElementTree.SubElement(cbWsdlPort,'soap:address') cbAddr.set('location',url) serviceName = self.__class__.__name__.split('.')[-1] portType = ElementTree.SubElement(root,'portType') portType.set('name',serviceName) for method in methods: if method.isCallback: operation = ElementTree.SubElement(callbackPortType,'operation') else: operation = ElementTree.SubElement(portType,'operation') operation.set('name',method.name) params = [] for name,param in method.inMessage.params: params.append(name) documentation = ElementTree.SubElement(operation,'documentation') documentation.text = method.doc operation.set('parameterOrder',method.inMessage.typ) opInput = ElementTree.SubElement(operation,'input') opInput.set('name',method.inMessage.typ) opInput.set('message','tns:%s'%method.inMessage.typ) if method.outMessage.params != None and not method.isCallback and not method.isAsync: opOutput = ElementTree.SubElement(operation,'output') opOutput.set('name',method.outMessage.typ) opOutput.set('message','tns:%s'%method.outMessage.typ) # make partner link plink = ElementTree.SubElement(root,'plnk:partnerLinkType') plink.set('name',serviceName) role = ElementTree.SubElement(plink,'plnk:role') role.set('name', serviceName) plinkPortType = ElementTree.SubElement(role,'plnk:portType') plinkPortType.set('name','tns:%s'%serviceName) if hasCallbacks: role = ElementTree.SubElement(plink,'plnk:role') role.set('name', '%sCallback'%serviceName) plinkPortType = ElementTree.SubElement(role,'plnk:portType') plinkPortType.set('name','tns:%sCallback'%serviceName) self._add_bindings_for_methods(root,serviceName,methods) service = ElementTree.SubElement(root,'service') service.set('name',serviceName) wsdlPort = ElementTree.SubElement(service,'port') wsdlPort.set('name',serviceName) wsdlPort.set('binding','tns:%s'%serviceName) addr = ElementTree.SubElement(wsdlPort,'soap:address') addr.set('location',url) wsdl = ElementTree.tostring(root) wsdl = "<?xml version='1.0' encoding='utf-8' ?>%s"%(wsdl) #cache the wsdl for next time self.__wsdl__ = wsdl return self.__wsdl__
def apply_mtom(headers, envelope, params, paramvals): ''' Apply MTOM to a SOAP envelope, separating attachments into a MIME multipart message. References: XOP http://www.w3.org/TR/xop10/ MTOM http://www.w3.org/TR/soap12-mtom/ http://www.w3.org/Submission/soap11mtom10/ @param headers Headers dictionary of the SOAP message that would originally be sent. @param envelope SOAP envelope string that would have originally been sent. @param params params attribute from the Message object used for the SOAP @param paramvals values of the params, passed to Message.to_xml @return tuple of length 2 with dictionary of headers and string of body that can be sent with HTTPConnection ''' # grab the XML element of the message in the SOAP body soapmsg = StringIO(envelope) soaptree = ElementTree.parse(soapmsg) soapns = soaptree.getroot().tag.split('}')[0].strip('{') soapbody = soaptree.getroot().find("{%s}Body" % soapns) message = None for child in list(soapbody): if child.tag != "%sFault" % (soapns,): message = child break # Get additional parameters from original Content-Type ctarray = [] for n, v in headers.items(): if n.lower() == 'content-type': ctarray = v.split(';') break roottype = ctarray[0].strip() rootparams = {} for ctparam in ctarray[1:]: n, v = ctparam.strip().split('=') rootparams[n] = v.strip("\"'") # Set up initial MIME parts mtompkg = MIMEMultipart('related',boundary='?//<><>soaplib_MIME_boundary<>') rootpkg = None try: rootpkg = MIMEApplication(envelope,'xop+xml', encode_7or8bit) except NameError: rootpkg = MIMENonMultipart("application", "xop+xml") rootpkg.set_payload(envelope) encode_7or8bit(rootpkg) # Set up multipart headers. del(mtompkg['mime-version']) mtompkg.set_param('start-info',roottype) mtompkg.set_param('start','<soaplibEnvelope>') if headers.has_key('SOAPAction'): mtompkg.add_header('SOAPAction', headers.get('SOAPAction')) # Set up root SOAP part headers del(rootpkg['mime-version']) rootpkg.add_header('Content-ID','<soaplibEnvelope>') for n, v in rootparams.items(): rootpkg.set_param(n,v) rootpkg.set_param('type',roottype) mtompkg.attach(rootpkg) # Extract attachments from SOAP envelope. for i in range(len(params)): name, typ = params[i] if typ == Attachment: id = "soaplibAttachment_%s" % (len(mtompkg.get_payload()),) param = message[i] param.text = "" incl = ElementTree.SubElement( param, "{http://www.w3.org/2004/08/xop/include}Include" ) incl.attrib["href"] = "cid:%s" % id if paramvals[i].fileName and not paramvals[i].data: paramvals[i].load_from_file() data = paramvals[i].data attachment = None try: attachment = MIMEApplication(data, _encoder=encode_7or8bit) except NameError: attachment = MIMENonMultipart("application", "octet-stream") attachment.set_payload(data) encode_7or8bit(attachment) del(attachment['mime-version']) attachment.add_header('Content-ID','<%s>'%(id,)) mtompkg.attach(attachment) # Update SOAP envelope. soapmsg.close() soapmsg = StringIO() soaptree.write(soapmsg) rootpkg.set_payload(soapmsg.getvalue()) soapmsg.close() # extract body string from MIMEMultipart message bound = '--%s' % (mtompkg.get_boundary(),) marray = mtompkg.as_string().split(bound) mtombody = bound mtombody += bound.join(marray[1:]) # set Content-Length mtompkg.add_header("Content-Length", str(len(mtombody))) # extract dictionary of headers from MIMEMultipart message mtomheaders = {} for name, value in mtompkg.items(): mtomheaders[name] = value if len(mtompkg.get_payload()) <= 1: return (headers, envelope) return (mtomheaders, mtombody)