Ejemplo n.º 1
0
    def AsSOAP(self, **kw):

        header = self.DataForSOAPHeader()
        sw = SoapWriter(**kw)
        self.serialize(sw)
        if header is not None:
            sw.serialize_header(header, header.typecode, typed=False)
        return str(sw)
Ejemplo n.º 2
0
    def Send(self,
             url,
             opname,
             obj,
             nsdict={},
             soapaction=None,
             wsaction=None,
             endPointReference=None,
             soapheaders=(),
             **kw):
        '''Send a message.  If url is None, use the value from the
        constructor (else error). obj is the object (data) to send.
        Data may be described with a requesttypecode keyword, the default 
        is the class's typecode (if there is one), else Any.

        Try to serialize as a Struct, if this is not possible serialize an Array.  If 
        data is a sequence of built-in python data types, it will be serialized as an
        Array, unless requesttypecode is specified.

        arguments:
            url -- 
            opname -- struct wrapper
            obj -- python instance

        key word arguments:
            nsdict -- 
            soapaction --
            wsaction -- WS-Address Action, goes in SOAP Header.
            endPointReference --  set by calling party, must be an 
                EndPointReference type instance.
            soapheaders -- list of pyobj, typically w/typecode attribute.
                serialized in the SOAP:Header.
            requesttypecode -- 

        '''
        url = url or self.url
        endPointReference = endPointReference or self.endPointReference

        # Serialize the object.
        d = {}
        d.update(self.nsdict)
        d.update(nsdict)

        sw = SoapWriter(
            nsdict=d,
            header=True,
            outputclass=self.writerclass,
            encodingStyle=kw.get('encodingStyle'),
        )

        requesttypecode = kw.get('requesttypecode')
        if '_args' in kw:  #NamedParamBinding
            tc = requesttypecode or TC.Any(pname=opname, aslist=False)
            sw.serialize(kw['_args'], tc)
        elif not requesttypecode:
            tc = getattr(obj, 'typecode', None) or TC.Any(pname=opname,
                                                          aslist=False)
            try:
                if type(obj) in _seqtypes:
                    obj = dict([(i.typecode.pname, i) for i in obj])
            except AttributeError:
                # can't do anything but serialize this in a SOAP:Array
                tc = TC.Any(pname=opname, aslist=True)
            else:
                tc = TC.Any(pname=opname, aslist=False)

            sw.serialize(obj, tc)
        else:
            sw.serialize(obj, requesttypecode)

        for i in soapheaders:
            sw.serialize_header(i)

        #
        # Determine the SOAP auth element.  SOAP:Header element
        if self.auth_style & AUTH.zsibasic:
            sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass),
                                _AuthHeader.typecode)

        #
        # Serialize WS-Address
        if self.wsAddressURI is not None:
            if self.soapaction and wsaction.strip('\'"') != self.soapaction:
                raise WSActionException('soapAction(%s) and WS-Action(%s) must match'\
                    %(self.soapaction,wsaction))

            self.address = Address(url, self.wsAddressURI)
            self.address.setRequest(endPointReference, wsaction)
            self.address.serialize(sw)

        #
        # WS-Security Signature Handler
        if self.sig_handler is not None:
            self.sig_handler.sign(sw)

        scheme, netloc, path, nil, nil, nil = urllib.parse.urlparse(url)
        transport = self.transport
        if transport is None and url is not None:
            if scheme == 'https':
                transport = self.defaultHttpsTransport
            elif scheme == 'http':
                transport = self.defaultHttpTransport
            else:
                raise RuntimeError(
                    'must specify transport or url startswith https/http')

        # Send the request.
        if issubclass(transport, http.client.HTTPConnection) is False:
            raise TypeError('transport must be a HTTPConnection')

        soapdata = str(sw)
        self.h = transport(netloc, None, **self.transdict)
        self.h.connect()
        self.SendSOAPData(soapdata, url, soapaction, **kw)
Ejemplo n.º 3
0
    def Send(self, url, opname, obj, nsdict={}, soapaction=None, wsaction=None,
             endPointReference=None, soapheaders=(), **kw):
        '''Send a message.  If url is None, use the value from the
        constructor (else error). obj is the object (data) to send.
        Data may be described with a requesttypecode keyword, the default
        is the class's typecode (if there is one), else Any.

        Try to serialize as a Struct, if this is not possible serialize an Array.  If
        data is a sequence of built-in python data types, it will be serialized as an
        Array, unless requesttypecode is specified.

        arguments:
            url --
            opname -- struct wrapper
            obj -- python instance

        key word arguments:
            nsdict --
            soapaction --
            wsaction -- WS-Address Action, goes in SOAP Header.
            endPointReference --  set by calling party, must be an
                EndPointReference type instance.
            soapheaders -- list of pyobj, typically w/typecode attribute.
                serialized in the SOAP:Header.
            requesttypecode --

        '''
        url = url or self.url
        endPointReference = endPointReference or self.endPointReference

        # Serialize the object.
        d = {}
        d.update(self.nsdict)
        d.update(nsdict)

        sw = SoapWriter(nsdict=d, header=True, outputclass=self.writerclass,
                 encodingStyle=kw.get('encodingStyle'),)

        requesttypecode = kw.get('requesttypecode')
        if '_args' in kw: #NamedParamBinding
            tc = requesttypecode or TC.Any(pname=opname, aslist=False)
            sw.serialize(kw['_args'], tc)
        elif not requesttypecode:
            tc = getattr(obj, 'typecode', None) or TC.Any(pname=opname, aslist=False)
            try:
                if isinstance(obj, _seqtypes):
                    obj = dict([(i.typecode.pname,i) for i in obj])
            except AttributeError:
                # can't do anything but serialize this in a SOAP:Array
                tc = TC.Any(pname=opname, aslist=True)
            else:
                tc = TC.Any(pname=opname, aslist=False)

            sw.serialize(obj, tc)
        else:
            sw.serialize(obj, requesttypecode)

        for i in soapheaders:
            sw.serialize_header(i)

        #
        # Determine the SOAP auth element.  SOAP:Header element
        if self.auth_style & AUTH.zsibasic:
            sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass),
                _AuthHeader.typecode)

        #
        # Serialize WS-Address
        if self.wsAddressURI is not None:
            if self.soapaction and wsaction.strip('\'"') != self.soapaction:
                raise WSActionException('soapAction(%s) and WS-Action(%s) must match'
                    %(self.soapaction,wsaction))

            self.address = Address(url, self.wsAddressURI)
            self.address.setRequest(endPointReference, wsaction)
            self.address.serialize(sw)

        #
        # WS-Security Signature Handler
        if self.sig_handler is not None:
            self.sig_handler.sign(sw)

        scheme,netloc,_,_,_,_ = urlparse.urlparse(url)
        transport = self.transport
        if transport is None and url is not None:
            if scheme == 'https':
                transport = self.defaultHttpsTransport
            elif scheme == 'http':
                transport = self.defaultHttpTransport
            else:
                raise RuntimeError('must specify transport or url startswith https/http')

        # Send the request.
        if not issubclass(transport, httplib.HTTPConnection):
            raise TypeError('transport must be a HTTPConnection')

        soapdata = str(sw)
        self.local.h = transport(netloc, None, **self.transdict)
        self.local.h.connect()
        self.local.boundary = sw.getMIMEBoundary()
        self.local.startCID = sw.getStartCID()
        self.SendSOAPData(soapdata, url, soapaction, **kw)
Ejemplo n.º 4
0
                    return

                result = handler(*arg)
            else:
                try: kwarg = dict([ (str(e.localName),tc.parse(e, ps)) for e in data ])
                except EvaluateException, e:
                    SendFault(FaultFromZSIException(e), **kw)
                    return

                result = handler(**kwarg)

            # reponse typecode
            #tc = getattr(result, 'typecode', TC.Any(pname=what+'Response'))
            tc = TC.Any(pname=what+'Response')

        sw = SoapWriter(nsdict=nsdict)
        sw.serialize(result, tc)
        return SendResponse(str(sw), **kw)
    except Fault, e:
        return SendFault(e, **kw)
    except Exception, e:
        # Something went wrong, send a fault.
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)


def _ModPythonSendXML(text, code=200, **kw):
    req = kw['request']
    req.content_type = 'text/xml'
    req.content_length = len(text)
    req.send_http_header()
    req.write(text)
Ejemplo n.º 5
0
 def processResponse(cls, output, **kw):
     sw = SoapWriter(outputclass=cls.writerClass)
     sw.serialize(output)
     return sw
Ejemplo n.º 6
0
def _Dispatch(ps, modules, SendResponse, SendFault, nsdict={}, typesmodule=None,
              gettypecode=gettypecode, rpc=False, docstyle=False, **kw):
    '''Find a handler for the SOAP request in ps; search modules.
    Call SendResponse or SendFault to send the reply back, appropriately.

    Behaviors:
        default -- Call "handler" method with pyobj representation of body root, and return
            a self-describing request (w/typecode).  Parsing done via a typecode from
            typesmodule, or Any.

        docstyle -- Call "handler" method with ParsedSoap instance and parse result with an
          XML typecode (DOM). Behavior, wrap result in a body_root "Response" appended message.

        rpc -- Specify RPC wrapper of result. Behavior, ignore body root (RPC Wrapper)
           of request, parse all "parts" of message via individual typecodes.  Expect
           the handler to return the parts of the message, whether it is a dict, single instance,
           or a list try to serialize it as a Struct but if this is not possible put it in an Array.
           Parsing done via a typecode from typesmodule, or Any.

    '''
    global _client_binding
    try:
        what = str(ps.body_root.localName)

        # See what modules have the element name.
        if modules is None:
            modules = ( sys.modules['__main__'], )

        handlers = [ getattr(m, what) for m in modules if hasattr(m, what) ]
        if len(handlers) == 0:
            raise TypeError("Unknown method " + what)

        # Of those modules, see who's callable.
        handlers = [ h for h in handlers if isinstance(h, collections.Callable) ]
        if len(handlers) == 0:
            raise TypeError("Unimplemented method " + what)
        if len(handlers) > 1:
            raise TypeError("Multiple implementations found: %s" % handlers)
        handler = handlers[0]

        _client_binding = ClientBinding(ps)
        if docstyle:
            result = handler(ps.body_root)
            tc = TC.XML(aslist=1, pname=what+'Response')
        elif not rpc:
            try:
                tc = gettypecode(typesmodule, ps.body_root)
            except Exception:
                tc = TC.Any()

            try:
                arg = tc.parse(ps.body_root, ps)
            except EvaluateException as ex:
                SendFault(FaultFromZSIException(ex), **kw)
                return

            try:
                result = handler(arg)
            except Exception as ex:
                SendFault(FaultFromZSIException(ex), **kw)
                return

            try:
                tc = result.typecode
            except AttributeError as ex:
                SendFault(FaultFromZSIException(ex), **kw)
                return

        elif typesmodule is not None:
            kwargs = {}
            for e in _child_elements(ps.body_root):
                try:
                    tc = gettypecode(typesmodule, e)
                except Exception:
                    tc = TC.Any()

                try:
                    kwargs[str(e.localName)] = tc.parse(e, ps)
                except EvaluateException as ex:
                    SendFault(FaultFromZSIException(ex), **kw)
                    return

            result = handler(**kwargs)
            aslist = False
            # make sure data is wrapped, try to make this a Struct
            if isinstance(result,_seqtypes):
                for _ in result:
                    aslist = hasattr(result, 'typecode')
                    if aslist: break
            elif not isinstance(result, dict):
                aslist = not hasattr(result, 'typecode')
                result = (result,)

            tc = TC.Any(pname=what+'Response', aslist=aslist)
        else:
            # if this is an Array, call handler with list
            # if this is an Struct, call handler with dict
            tp = _find_type(ps.body_root)
            isarray = ((isinstance(tp, (tuple,list)) and tp[1] == 'Array') or _find_arraytype(ps.body_root))
            data = _child_elements(ps.body_root)
            tc = TC.Any()
            if isarray and len(data) == 0:
                result = handler()
            elif isarray:
                try: arg = [ tc.parse(e, ps) for e in data ]
                except EvaluateException as e:
                    #SendFault(FaultFromZSIException(e), **kw)
                    SendFault(RuntimeError("THIS IS AN ARRAY: %s" %isarray))
                    return

                result = handler(*arg)
            else:
                try: kwarg = dict([ (str(e.localName),tc.parse(e, ps)) for e in data ])
                except EvaluateException as e:
                    SendFault(FaultFromZSIException(e), **kw)
                    return

                result = handler(**kwarg)

            # reponse typecode
            #tc = getattr(result, 'typecode', TC.Any(pname=what+'Response'))
            tc = TC.Any(pname=what+'Response')

        sw = SoapWriter(nsdict=nsdict)
        sw.serialize(result, tc)
        return SendResponse(str(sw), **kw)
    except Fault as e:
        return SendFault(e, **kw)
    except Exception as e:
        # Something went wrong, send a fault.
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
Ejemplo n.º 7
0
                result = handler(*arg)
            else:
                try:
                    kwarg = dict([(str(e.localName), tc.parse(e, ps))
                                  for e in data])
                except EvaluateException, e:
                    SendFault(FaultFromZSIException(e), **kw)
                    return

                result = handler(**kwarg)

            # reponse typecode
            #tc = getattr(result, 'typecode', TC.Any(pname=what+'Response'))
            tc = TC.Any(pname=what + 'Response')

        sw = SoapWriter(nsdict=nsdict)
        sw.serialize(result, tc)
        return SendResponse(str(sw), **kw)
    except Fault, e:
        return SendFault(e, **kw)
    except Exception, e:
        # Something went wrong, send a fault.
        return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)


def _ModPythonSendXML(text, code=200, **kw):
    req = kw['request']
    req.content_type = 'text/xml'
    req.content_length = len(text)
    req.send_http_header()
    req.write(text)