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

Python simplexml.SimpleXMLElement类代码示例

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

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



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

示例1: call

    def call(self, method, *args, **kwargs):
        "Prepare xml request and make SOAP call, returning a SimpleXMLElement"                
        #TODO: method != input_message
        # Basic SOAP request:
        if kwargs:
            parameters = kwargs.items()
            username, password = args
        else:
            (username, password), parameters = args
        
        created = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')

        expires = (datetime.utcnow() + timedelta(0, 300)).strftime('%Y-%m-%dT%H:%M:%SZ')
        
        header = self.header
        try:
            header = header % dict(Username = username, Password = password, Created=created, Expires=expires)
        except KeyError:
            pass
        
        xml = self.__xml % dict(method=method, namespace=self.namespace, ns=self.__ns, header = header,
                                soap_ns=self.__soap_ns, soap_uri=soap_namespaces[self.__soap_ns], body_xmlns = self.body_xmlns)
        
        request = SimpleXMLElement(xml,namespace=self.__ns and self.namespace, prefix=self.__ns)
        # serialize parameters

        if parameters and isinstance(parameters[0], SimpleXMLElement):
            # merge xmlelement parameter ("raw" - already marshalled)
            for param in parameters[0].children():
                getattr(request,method).import_node(param)
        else:
            # marshall parameters:
            for k,v in parameters: # dict: tag=valor
                getattr(request,method).marshall(k,v)
        
        self.xml_request = request.as_xml()
        
        try:
            self.xml_response = self.send(method, self.xml_request)
            response = SimpleXMLElement(self.xml_response, namespace=self.namespace)
            if self.exceptions and response("Fault", ns=soap_namespaces.values(), error=False):
                raise SoapFault(unicode(response.faultcode), unicode(response.faultstring))
            return response
        except urllib2.HTTPError, error:
            self.xml_response = error.read()
            try:
                response = SimpleXMLElement(self.xml_response, namespace=self.namespace)
            except:
                raise error
            if self.exceptions and response("Fault", ns=soap_namespaces.values(), error=False):
                try:
                    detail = str(response.detail.Message)
                except:
                    detail = ""
                if "ID3242" in detail:
                    raise NotAuthorizedError()
                else:
                    raise SoapFault(unicode(response.faultcode), unicode(response.faultstring))
            else:
                raise error
开发者ID:atomia,项目名称:AutomationServerManager,代码行数:60,代码来源:client.py


示例2: help

    def help(self, method=None):
        "Generate sample request and response messages"
        (function, returns, args, doc) = self.methods[method]
        xml = """
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body><%(method)s xmlns="%(namespace)s"/></soap:Body>
</soap:Envelope>"""  % {'method':method, 'namespace':self.namespace}
        request = SimpleXMLElement(xml, namespace=self.namespace, prefix=self.prefix)
        if args:
            items = args.items()
        elif args is None:
            items = [('value', None)]
        else:
            items = []
        for k,v in items:
            request(method).marshall(k, v, add_comments=True, ns=False)

        xml = """
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body><%(method)sResponse xmlns="%(namespace)s"/></soap:Body>
</soap:Envelope>"""  % {'method':method, 'namespace':self.namespace}
        response = SimpleXMLElement(xml, namespace=self.namespace, prefix=self.prefix)
        if returns:
            items = returns.items()
        elif args is None:
            items = [('value', None)]
        else:
            items = []
        for k,v in items:
            response('%sResponse'%method).marshall(k, v, add_comments=True, ns=False)

        return request.as_xml(pretty=True), response.as_xml(pretty=True), doc
开发者ID:BlackgateResearch,项目名称:Pip-Target,代码行数:32,代码来源:server.py


示例3: dispatch

    def dispatch(self, xml, action=None):
        "Receive and proccess SOAP call"
        # default values:
        prefix = self.prefix
        ret = fault = None
        soap_ns, soap_uri = self.soap_ns, self.soap_uri
        soap_fault_code = 'VersionMismatch'
        name = None

        try:
            request = SimpleXMLElement(xml, namespace=self.namespace)

            # detect soap prefix and uri (xmlns attributes of Envelope)
            for k, v in request[:]:
                if v in ("http://schemas.xmlsoap.org/soap/envelope/",
                                  "http://www.w3.org/2003/05/soap-env",):
                    soap_ns = request.attributes()[k].localName
                    soap_uri = request.attributes()[k].value
            
            soap_fault_code = 'Client'
            
            # parse request message and get local method            
            method = request('Body', ns=soap_uri).children()(0)
            if action:
                # method name = action 
                name = action[len(self.action)+1:-1]
                prefix = self.prefix
            if not action or not name:
                # method name = input message name
                name = method.get_local_name()
                prefix = method.get_prefix()

            log.debug('dispatch method %s', name)
            function, returns_types, args_types, doc = self.methods[name]
        
            # de-serialize parameters (if type definitions given)
            if args_types:
                args = method.children().unmarshall(args_types)
            elif args_types is None:
                args = {'request':method} # send raw request
            else:
                args = {} # no parameters
 
            soap_fault_code = 'Server'
            # execute function
            ret = function(**args)
            log.debug('%s', ret)

        except Exception, e:
            import sys
            etype, evalue, etb = sys.exc_info()
            if DEBUG: 
                import traceback
                detail = ''.join(traceback.format_exception(etype, evalue, etb))
                detail += '\n\nXML REQUEST\n\n' + xml
            else:
                detail = None
            fault = {'faultcode': "%s.%s" % (soap_fault_code, etype.__name__), 
                     'faultstring': unicode(evalue), 
                     'detail': detail}
开发者ID:Homidom,项目名称:HoMIDoM-Plugin-XBMC-KODI,代码行数:60,代码来源:server.py


示例4: call

 def call(self, method, *args, **kwargs):
     "Prepare xml request and make SOAP call, returning a SimpleXMLElement"                
     #TODO: method != input_message
     # Basic SOAP request:
     xml = self.__xml % dict(method=method, namespace=self.namespace, ns=self.__ns,
                             soap_ns=self.__soap_ns, soap_uri=soap_namespaces[self.__soap_ns])
     request = SimpleXMLElement(xml,namespace=self.__ns and self.namespace, prefix=self.__ns)
     # serialize parameters
     if kwargs:
         parameters = kwargs.items()
     else:
         parameters = args
     if parameters and isinstance(parameters[0], SimpleXMLElement):
         # merge xmlelement parameter ("raw" - already marshalled)
         for param in parameters[0].children():
             getattr(request,method).import_node(param)
     elif parameters:
         # marshall parameters:
         for k,v in parameters: # dict: tag=valor
             getattr(request,method).marshall(k,v)
     elif not self.__soap_server in ('oracle', ) or self.__soap_server in ('jbossas6',):
         # JBossAS-6 requires no empty method parameters!
         delattr(request("Body", ns=soap_namespaces.values(),), method)
     # construct header and parameters (if not wsdl given) except wsse
     if self.__headers and not self.services:
         self.__call_headers = dict([(k, v) for k, v in self.__headers.items()
                                     if not k.startswith("wsse:")])
     # always extract WS Security header and send it
     if 'wsse:Security' in self.__headers:
         #TODO: namespaces too hardwired, clean-up...
         header = request('Header' , ns=soap_namespaces.values(),)
         k = 'wsse:Security'
         v = self.__headers[k]
         header.marshall(k, v, ns=False, add_children_ns=False)
         header(k)['xmlns:wsse'] = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'
         #<wsse:UsernameToken xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'> 
     if self.__call_headers:
         header = request('Header' , ns=soap_namespaces.values(),)
         for k, v in self.__call_headers.items():
             ##if not self.__ns:
             ##    header['xmlns']
             header.marshall(k, v, ns=self.__ns, add_children_ns=False)
     self.xml_request = request.as_xml()
     self.xml_response = self.send(method, self.xml_request)
     response = SimpleXMLElement(self.xml_response, namespace=self.namespace)
     if self.exceptions and response("Fault", ns=soap_namespaces.values(), error=False):
         raise SoapFault(unicode(response.faultcode), unicode(response.faultstring))
     return response
开发者ID:carriercomm,项目名称:pcoip-utils,代码行数:48,代码来源:client.py


示例5: wsdl

    def wsdl(self):
        "Generate Web Service Description v1.1"
        xml = """<?xml version="1.0"?>
<wsdl:definitions name="%(name)s" 
          targetNamespace="%(namespace)s"
          xmlns:tns="%(namespace)s"
          xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
          xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">%(documentation)s</wsdl:documentation>

    <wsdl:types>
       <xsd:schema targetNamespace="%(namespace)s"
              elementFormDefault="qualified"
              xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       </xsd:schema>
    </wsdl:types>

</wsdl:definitions>
""" % {'namespace': self.namespace, 'name': self.name, 'documentation': self.documentation}
        wsdl = SimpleXMLElement(xml)

        for method, (function, returns, args, doc) in self.methods.items():
            # create elements:
                
            def parse_element(name, values, array=False, complex=False):
                if not complex:
                    element = wsdl('wsdl:types')('xsd:schema').add_child('xsd:element')
                    complex = element.add_child("xsd:complexType")
                else:
                    complex = wsdl('wsdl:types')('xsd:schema').add_child('xsd:complexType')
                    element = complex
                element['name'] = name
                if values:
                    items = values
                elif values is None:
                    items = [('value', None)]
                else:
                    items = []
                if not array and items:
                    all = complex.add_child("xsd:all")
                elif items:
                    all = complex.add_child("xsd:sequence")
                for k,v in items:
                    e = all.add_child("xsd:element")
                    e['name'] = k
                    if array:
                        e[:]={'minOccurs': "0", 'maxOccurs': "unbounded"}
                    if v in TYPE_MAP.keys():
                        t='xsd:%s' % TYPE_MAP[v]
                    elif v is None:
                        t='xsd:anyType'
                    elif isinstance(v, list):
                        n="ArrayOf%s%s" % (name, k)
                        l = []
                        for d in v:
                            l.extend(d.items())
                        parse_element(n, l, array=True, complex=True)
                        t = "tns:%s" % n
                    elif isinstance(v, dict): 
                        n="%s%s" % (name, k)
                        parse_element(n, v.items(), complex=True)
                        t = "tns:%s" % n
                    e.add_attribute('type', t)
            
            parse_element("%s" % method, args and args.items())
            parse_element("%sResponse" % method, returns and returns.items())

            # create messages:
            for m,e in ('Input',''), ('Output','Response'):
                message = wsdl.add_child('wsdl:message')
                message['name'] = "%s%s" % (method, m)
                part = message.add_child("wsdl:part")
                part[:] = {'name': 'parameters', 
                           'element': 'tns:%s%s' % (method,e)}

        # create ports
        portType = wsdl.add_child('wsdl:portType')
        portType['name'] = "%sPortType" % self.name
        for method, (function, returns, args, doc) in self.methods.items():
            op = portType.add_child('wsdl:operation')
            op['name'] = method
            if doc:
                op.add_child("wsdl:documentation", doc)
            input = op.add_child("wsdl:input")
            input['message'] = "tns:%sInput" % method
            output = op.add_child("wsdl:output")
            output['message'] = "tns:%sOutput" % method

        # create bindings
        binding = wsdl.add_child('wsdl:binding')
        binding['name'] = "%sBinding" % self.name
        binding['type'] = "tns:%sPortType" % self.name
        soapbinding = binding.add_child('soap:binding')
        soapbinding['style'] = "document"
        soapbinding['transport'] = "http://schemas.xmlsoap.org/soap/http"
        for method in self.methods.keys():
            op = binding.add_child('wsdl:operation')
            op['name'] = method
            soapop = op.add_child('soap:operation')
#.........这里部分代码省略.........
开发者ID:BlackgateResearch,项目名称:Pip-Target,代码行数:101,代码来源:server.py


示例6: dispatch

    def dispatch(self, xml, action=None):
        "Receive and proccess SOAP call"
        # default values:
        prefix = self.prefix
        ret = fault = None
        soap_ns, soap_uri = self.soap_ns, self.soap_uri
        soap_fault_code = 'VersionMismatch'
        name = None
        
        # namespaces = [('model', 'http://model.common.mt.moboperator'), ('external', 'http://external.mt.moboperator')]
        _ns_reversed = dict(((v,k) for k,v in self.namespaces.iteritems())) # Switch keys-values
        # _ns_reversed = {'http://external.mt.moboperator': 'external', 'http://model.common.mt.moboperator': 'model'}
        
        try:
            request = SimpleXMLElement(xml, namespace=self.namespace)
            
            # detect soap prefix and uri (xmlns attributes of Envelope)
            for k, v in request[:]:
                if v in ("http://schemas.xmlsoap.org/soap/envelope/",
                                  "http://www.w3.org/2003/05/soap-env",):
                    soap_ns = request.attributes()[k].localName
                    soap_uri = request.attributes()[k].value
                
                # If the value from attributes on Envelope is in additional namespaces
                elif v in self.namespaces.values():
                    _ns = request.attributes()[k].localName
                    _uri = request.attributes()[k].value
                    _ns_reversed[_uri] = _ns # update with received alias
                    # Now we change 'external' and 'model' to the received forms i.e. 'ext' and 'mod'
                # After that we know how the client has prefixed additional namespaces
            
            ns = NS_RX.findall(xml)
            for k, v in ns:
                if v in self.namespaces.values():
                    _ns_reversed[v] = k
            
            soap_fault_code = 'Client'
            
            # parse request message and get local method
            method = request('Body', ns=soap_uri).children()(0)
            if action:
                # method name = action 
                name = action[len(self.action)+1:-1]
                prefix = self.prefix
            if not action or not name:
                # method name = input message name
                name = method.get_local_name()
                prefix = method.get_prefix()

            log.debug('dispatch method: %s', name)
            function, returns_types, args_types, doc = self.methods[name]
            log.debug('returns_types %s', returns_types)
            
            # de-serialize parameters (if type definitions given)
            if args_types:
                args = method.children().unmarshall(args_types)
            elif args_types is None:
                args = {'request': method} # send raw request
            else:
                args = {} # no parameters
            
            soap_fault_code = 'Server'
            # execute function
            ret = function(**args)
            log.debug('dispathed method returns: %s', ret)

        except Exception: # This shouldn't be one huge try/except
            import sys
            etype, evalue, etb = sys.exc_info()
            log.error(traceback.format_exc())
            if self.debug:
                detail = ''.join(traceback.format_exception(etype, evalue, etb))
                detail += '\n\nXML REQUEST\n\n' + xml
            else:
                detail = None
            fault = {'faultcode': "%s.%s" % (soap_fault_code, etype.__name__), 
                     'faultstring': unicode(evalue), 
                     'detail': detail}

        # build response message
        if not prefix:
            xml = """<%(soap_ns)s:Envelope xmlns:%(soap_ns)s="%(soap_uri)s"/>"""  
        else:
            xml = """<%(soap_ns)s:Envelope xmlns:%(soap_ns)s="%(soap_uri)s"
                       xmlns:%(prefix)s="%(namespace)s"/>"""  
            
        xml %= {    # a %= {} is a shortcut for a = a % {}
            'namespace': self.namespace, 
            'prefix': prefix,
            'soap_ns': soap_ns, 
            'soap_uri': soap_uri
        }
        
        # Now we add extra namespaces
        xml = SoapDispatcher._extra_namespaces(xml, _ns_reversed)
        
        # Change our namespace alias to that given by the client.
        # We put [('model', 'http://model.common.mt.moboperator'), ('external', 'http://external.mt.moboperator')]
        # mix it with {'http://external.mt.moboperator': 'ext', 'http://model.common.mt.moboperator': 'mod'}
        mapping = dict(((k, _ns_reversed[v]) for k,v in self.namespaces.iteritems())) # Switch keys-values and change value
#.........这里部分代码省略.........
开发者ID:2089764,项目名称:web2py,代码行数:101,代码来源:server.py


示例7: wsdl_parse

    def wsdl_parse(self, url, debug=False, cache=False):
        "Parse Web Service Description v1.1"

        if debug: print "wsdl url: %s" % url
        # Try to load a previously parsed wsdl:
        force_download = False
        if cache:
            # make md5 hash of the url for caching... 
            filename_pkl = "%s.pkl" % hashlib.md5(url).hexdigest()
            if isinstance(cache, basestring):
                filename_pkl = os.path.join(cache, filename_pkl) 
            if os.path.exists(filename_pkl):
                if debug: print "Unpickle file %s" % (filename_pkl, )
                f = open(filename_pkl, "r")
                pkl = pickle.load(f)
                f.close()
                # sanity check:
                if pkl['version'][:-1] != __version__.split(" ")[0][:-1] or pkl['url'] != url:
                    import warnings
                    warnings.warn('version or url mismatch! discarding cached wsdl', RuntimeWarning) 
                    if debug:
                        print 'Version:', pkl['version'], __version__
                        print 'URL:', pkl['url'], url
                    force_download = True
                else:
                    self.namespace = pkl['namespace']
                    self.documentation = pkl['documentation']
                    return pkl['services']
        
        soap_ns = {
            "http://schemas.xmlsoap.org/wsdl/soap/": 'soap11',
            "http://schemas.xmlsoap.org/wsdl/soap12/": 'soap12',
            }
        wsdl_uri="http://schemas.xmlsoap.org/wsdl/"
        xsd_uri="http://www.w3.org/2001/XMLSchema"
        xsi_uri="http://www.w3.org/2001/XMLSchema-instance"
        
        get_local_name = lambda s: str((':' in s) and s.split(':')[1] or s)
        
        REVERSE_TYPE_MAP = dict([(v,k) for k,v in TYPE_MAP.items()])

        def fetch(url):
            "Download a document from a URL, save it locally if cache enabled"
            # make md5 hash of the url for caching... 
            filename = "%s.xml" % hashlib.md5(url).hexdigest()
            if isinstance(cache, basestring):
                filename = os.path.join(cache, filename) 
            if cache and os.path.exists(filename) and not force_download:
                if debug: print "Reading file %s" % (filename, )
                f = open(filename, "r")
                xml = f.read()
                f.close()
            else:
                if debug: print "Fetching url %s using urllib2" % (url, )
                f = urllib2.urlopen(url)
                xml = f.read()
                if cache:
                    if debug: print "Writing file %s" % (filename, )
                    if not os.path.isdir(cache):
                        os.makedirs(cache)
                    f = open(filename, "w")
                    f.write(xml)
                    f.close()
            return xml
            
        # Open uri and read xml:
        xml = fetch(url)
        # Parse WSDL XML:
        wsdl = SimpleXMLElement(xml, namespace=wsdl_uri)

        # detect soap prefix and uri (xmlns attributes of <definitions>)
        xsd_ns = None
        soap_uris = {}
        for k, v in wsdl[:]:
            if v in soap_ns and k.startswith("xmlns:"):
                soap_uris[get_local_name(k)] = v
            if v== xsd_uri and k.startswith("xmlns:"):
                xsd_ns = get_local_name(k)

        # Extract useful data:
        self.namespace = wsdl['targetNamespace']
        self.documentation = unicode(wsdl('documentation', error=False) or '')
        
        services = {}
        bindings = {}           # binding_name: binding
        operations = {}         # operation_name: operation
        port_type_bindings = {} # port_type_name: binding
        messages = {}           # message: element
        elements = {}           # element: type def
        
        for service in wsdl.service:
            service_name=service['name']
            if not service_name:
                continue # empty service?
            if debug: print "Processing service", service_name
            serv = services.setdefault(service_name, {'ports': {}})
            serv['documentation']=service['documentation'] or ''
            for port in service.port:
                binding_name = get_local_name(port['binding'])
                address = port('address', ns=soap_uris.values(), error=False)
#.........这里部分代码省略.........
开发者ID:AndresVillan,项目名称:pyafipws.web2py-app,代码行数:101,代码来源:client.py


示例8: wsdl

    def wsdl(self, url, debug=False):
        "Parse Web Service Description v1.1"
        soap_ns = {
            "http://schemas.xmlsoap.org/wsdl/soap/": 'soap11',
            "http://schemas.xmlsoap.org/wsdl/soap12/": 'soap12',
            }
        wsdl_uri="http://schemas.xmlsoap.org/wsdl/"
        xsd_uri="http://www.w3.org/2001/XMLSchema"
        xsi_uri="http://www.w3.org/2001/XMLSchema-instance"
        
        get_local_name = lambda s: str((':' in s) and s.split(':')[1] or s)
        
        REVERSE_TYPE_MAP = dict([(v,k) for k,v in TYPE_MAP.items()])
        
        # Open uri and read xml:
        f = urllib.urlopen(url)
        xml = f.read()
        # Parse WSDL XML:
        wsdl = SimpleXMLElement(xml, namespace=wsdl_uri)

        # detect soap prefix and uri (xmlns attributes of <definitions>)
        xsd_ns = None
        soap_uris = {}
        for k, v in wsdl[:]:
            if v in soap_ns and k.startswith("xmlns:"):
                soap_uris[get_local_name(k)] = v
            if v== xsd_uri and k.startswith("xmlns:"):
                xsd_ns = get_local_name(k)

        # Extract useful data:
        self.namespace = wsdl['targetNamespace']
        self.documentation = unicode(wsdl('documentation', error=False) or '')
        
        services = {}
        bindings = {}           # binding_name: binding
        operations = {}         # operation_name: operation
        port_type_bindings = {} # port_type_name: binding
        messages = {}           # message: element
        elements = {}           # element: type def
        
        for service in wsdl.service:
            service_name=service['name']
            if debug: print "Processing service", service_name
            serv = services.setdefault(service_name, {'ports': {}})
            serv['documentation']=service['documentation'] or ''
            for port in service.port:
                binding_name = get_local_name(port['binding'])
                address = port('address', ns=soap_uris.values(), error=False)
                location = address and address['location'] or None
                soap_uri = address and soap_uris.get(address.get_prefix())
                soap_ver = soap_uri and soap_ns.get(soap_uri)
                bindings[binding_name] = {'service_name': service_name,
                    'location': location, 
                    'soap_uri': soap_uri, 'soap_ver': soap_ver,
                    }
                serv['ports'][port['name']] = bindings[binding_name]
             
        for binding in wsdl.binding:
            binding_name = binding['name']
            if debug: print "Processing binding", service_name
            soap_binding = binding('binding', ns=soap_uris.values(), error=False)
            transport = soap_binding and soap_binding['transport'] or None
            port_type_name = get_local_name(binding['type'])
            bindings[binding_name].update({
                'port_type_name': port_type_name,
                'transport': transport, 'operations': {},
                })
            port_type_bindings[port_type_name] = bindings[binding_name]
            for operation in binding.operation:
                op_name = operation['name']
                op = operation('operation',ns=soap_uris.values(), error=False)
                action = op and op['soapAction']
                d = operations.setdefault(op_name, {})
                bindings[binding_name]['operations'][op_name] = d
                d.update({'name': op_name})
                #if action: #TODO: separe operation_binding from operation
                d["action"] = action
        
        def process_element(element_name, children):
            if debug: print "Processing element", element_name
            for tag in children:
                d = OrderedDict()
                for e in tag.children():
                    t = e['type'].split(":")
                    if len(t)>1:
                        ns, type_name = t
                    else:
                        ns, type_name = xsd_ns, t[0]
                    if ns==xsd_ns:
                        # look for the type, None == any
                        fn = REVERSE_TYPE_MAP.get(unicode(type_name), None)
                    else:
                        # complex type, postprocess later
                        fn = elements.setdefault(unicode(type_name), OrderedDict())
                    e_name = unicode(e['name'])
                    d[e_name] = fn
                    if e['maxOccurs']=="unbounded":
                        # it's an array... TODO: compound arrays?
                        d.array = True
                elements.setdefault(element_name, OrderedDict()).update(d)
#.........这里部分代码省略.........
开发者ID:BlackgateResearch,项目名称:Pip-Target,代码行数:101,代码来源:client.py


示例9: wsdl_parse

    def wsdl_parse(self, url, cache=False):
        "Parse Web Service Description v1.1"

        log.debug("wsdl url: %s" % url)
        # Try to load a previously parsed wsdl:
        force_download = False
        if cache:
            # make md5 hash of the url for caching...
            filename_pkl = "%s.pkl" % hashlib.md5(url).hexdigest()
            if isinstance(cache, basestring):
                filename_pkl = os.path.join(cache, filename_pkl)
            if os.path.exists(filename_pkl):
                log.debug("Unpickle file %s" % (filename_pkl,))
                f = open(filename_pkl, "r")
                pkl = pickle.load(f)
                f.close()
                # sanity check:
                if pkl["version"][:-1] != __version__.split(" ")[0][:-1] or pkl["url"] != url:
                    import warnings

                    warnings.warn("version or url mismatch! discarding cached wsdl", RuntimeWarning)
                    log.debug("Version: %s %s" % (pkl["version"], __version__))
                    log.debug("URL: %s %s" % (pkl["url"], url))
                    force_download = True
                else:
                    self.namespace = pkl["namespace"]
                    self.documentation = pkl["documentation"]
                    return pkl["services"]

        soap_ns = {
            "http://schemas.xmlsoap.org/wsdl/soap/": "soap11",
            "http://schemas.xmlsoap.org/wsdl/soap12/": "soap12",
        }
        wsdl_uri = "http://schemas.xmlsoap.org/wsdl/"
        xsd_uri = "http://www.w3.org/2001/XMLSchema"
        xsi_uri = "http://www.w3.org/2001/XMLSchema-instance"

        get_local_name = lambda s: s and str((":" in s) and s.split(":")[1] or s)
        get_namespace_prefix = lambda s: s and str((":" in s) and s.split(":")[0] or None)

        # always return an unicode object:
        REVERSE_TYPE_MAP[u"string"] = unicode

        # Open uri and read xml:
        xml = fetch(url, self.http, cache, force_download, self.wsdl_basedir)
        # Parse WSDL XML:
        wsdl = SimpleXMLElement(xml, namespace=wsdl_uri)

        # detect soap prefix and uri (xmlns attributes of <definitions>)
        xsd_ns = None
        soap_uris = {}
        for k, v in wsdl[:]:
            if v in soap_ns and k.startswith("xmlns:"):
                soap_uris[get_local_name(k)] = v
            if v == xsd_uri and k.startswith("xmlns:"):
                xsd_ns = get_local_name(k)

        # Extract useful data:
        self.namespace = wsdl["targetNamespace"]
        self.documentation = unicode(wsdl("documentation", error=False) or "")

        services = {}
        bindings = {}  # binding_name: binding
        operations = {}  # operation_name: operation
        port_type_bindings = {}  # port_type_name: binding
        messages = {}  # message: element
        elements = {}  # element: type def

        for service in wsdl.service:
            service_name = service["name"]
            if not service_name:
                continue  # empty service?
            log.debug("Processing service %s" % service_name)
            serv = services.setdefault(service_name, {"ports": {}})
            serv["documentation"] = service["documentation"] or ""
            for port in service.port:
                binding_name = get_local_name(port["binding"])
                operations[binding_name] = {}
                address = port("address", ns=soap_uris.values(), error=False)
                location = address and address["location"] or None
                soap_uri = address and soap_uris.get(address.get_prefix())
                soap_ver = soap_uri and soap_ns.get(soap_uri)
                bindings[binding_name] = {
                    "name": binding_name,
                    "service_name": service_name,
                    "location": location,
                    "soap_uri": soap_uri,
                    "soap_ver": soap_ver,
                }
                serv["ports"][port["name"]] = bindings[binding_name]

        for binding in wsdl.binding:
            binding_name = binding["name"]
            soap_binding = binding("binding", ns=soap_uris.values(), error=False)
            transport = soap_binding and soap_binding["transport"] or None
            port_type_name = get_local_name(binding["type"])
            bindings[binding_name].update({"port_type_name": port_type_name, "transport": transport, "operations": {}})
            if port_type_name not in port_type_bindings:
                port_type_bindings[port_type_name] = []
            port_type_bindings[port_type_name].append(bindings[binding_name])
#.........这里部分代码省略.........
开发者ID:yashodhank,项目名称:digital-signage-server,代码行数:101,代码来源:client.py


示例10: call

    def call(self, method, *args, **kwargs):
        """Prepare xml request and make SOAP call, returning a SimpleXMLElement.

        If a keyword argument called "headers" is passed with a value of a
        SimpleXMLElement object, then these headers will be inserted into the
        request.
        """
        # TODO: method != input_message
        # Basic SOAP request:
        xml = self.__xml % dict(
            method=method,
            namespace=self.namespace,
            ns=self.__ns,
            soap_ns=self.__soap_ns,
            soap_uri=soap_namespaces[self.__soap_ns],
        )
        request = SimpleXMLElement(xml, namespace=self.__ns and self.namespace, prefix=self.__ns)

        try:
            request_headers = kwargs.pop("headers")
        except KeyError:
            request_headers = None

        # serialize parameters
        if kwargs:
            parameters = kwargs.items()
        else:
            parameters = args
        if parameters and isinstance(parameters[0], SimpleXMLElement):
            # merge xmlelement parameter ("raw" - already marshalled)
            if parameters[0].children() is not None:
                for param in parameters[0].children():
                    getattr(request, method).import_node(param)
        elif parameters:
            # marshall parameters:
            for k, v in parameters:  # dict: tag=valor
                getattr(request, method).marshall(k, v)
        elif not self.__soap_server in ("oracle",) or self.__soap_server in ("jbossas6",):
            # JBossAS-6 requires no empty method parameters!
            delattr(request("Body", ns=soap_namespaces.values()), method)

        # construct header and parameters (if not wsdl given) except wsse
        if self.__headers and not self.services:
            self.__call_headers = dict([(k, v) for k, v in self.__headers.items() if not k.startswith("wsse:")])
        # always extract WS Security header and send it
        if "wsse:Security" in self.__headers:
            # TODO: namespaces too hardwired, clean-up...
            header = request("Header", ns=soap_namespaces.values())
            k = "wsse:Security"
            v = self.__headers[k]
            header.marshall(k, v, ns=False, add_children_ns=False)
            header(k)[
                "xmlns:wsse"
            ] = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
            # <wsse:UsernameToken xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'>
        if self.__call_headers:
            header = request("Header", ns=soap_namespaces.values())
            for k, v in self.__call_headers.items():
                ##if not self.__ns:
                ##    header['xmlns']
                if isinstance(v, SimpleXMLElement):
                    # allows a SimpleXMLElement to be constructed and inserted
                    # rather than a dictionary. marshall doesn't allow ns: prefixes
                    # in dict key names
                    header.import_node(v)
                else:
                    header.marshall(k, v, ns=self.__ns, add_children_ns=False)
        if request_headers:
            header = request("Header", ns=soap_namespaces.values())
            for subheader in request_headers.children():
                header.import_node(subheader)

        self.xml_request = request.as_xml()
        self.xml_response = self.send(method, self.xml_request)
        response = SimpleXMLElement(self.xml_response, namespace=self.namespace, jetty=self.__soap_server in ("jetty",))
        if self.exceptions and response("Fault", ns=soap_namespaces.values(), error=False):
            raise SoapFault(unicode(response.faultcode), unicode(response.faultstring))
        return response
开发者ID:yashodhank,项目名称:digital-signage-server,代码行数:78,代码来源:client.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python simport.load函数代码示例发布时间:2022-05-27
下一篇:
Python simplexml.Node类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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