def __call__(self, **params): # Pull out arguments that Send() uses kw = {} for key in ['auth_header', 'nsdict', 'requesttypecode', 'soapaction']: if key in params: kw[key] = params[key] del params[key] nsuri = self.namespace if nsuri is None: return self.binding.RPC( None, self.name, None, encodingStyle="http://schemas.xmlsoap.org/soap/encoding/", _args=params, replytype=TC.Any(self.name + "Response", aslist=False), **kw) return self.binding.RPC( None, (nsuri, self.name), None, encodingStyle="http://schemas.xmlsoap.org/soap/encoding/", _args=params, replytype=TC.Any((nsuri, self.name + "Response"), aslist=False), **kw)
def __call__(self, *args): nsuri = self.namespace if nsuri is None: return self.binding.RPC( None, self.name, args, encodingStyle="http://schemas.xmlsoap.org/soap/encoding/", replytype=TC.Any(self.name + "Response")) return self.binding.RPC( None, (nsuri, self.name), args, encodingStyle="http://schemas.xmlsoap.org/soap/encoding/", replytype=TC.Any((nsuri, self.name + "Response")))
def __parse_child(self, node): '''for rpc-style map each message part to a class in typesmodule ''' try: tc = self.gettypecode(self.typesmodule, node) except: self.logger.debug( 'didnt find typecode for "%s" in typesmodule: %s', node.localName, self.typesmodule) tc = TC.Any(aslist=1) return tc.parse(node, self.ps) self.logger.debug('parse child with typecode : %s', tc) try: return tc.parse(node, self.ps) except Exception: self.logger.debug('parse failed try Any : %s', tc) tc = TC.Any(aslist=1) return tc.parse(node, self.ps)
## ## Importing the rest of ZSI. def Version(): from pysphere.ZSI import version return version.Version from pysphere.ZSI.writer import SoapWriter from pysphere.ZSI.parse import ParsedSoap from pysphere.ZSI.fault import Fault, \ FaultFromActor, FaultFromException, FaultFromFaultMessage, \ FaultFromNotUnderstood, FaultFromZSIException from pysphere.ZSI import TC TC.RegisterType(TC.String, minOccurs=0, nillable=False) TC.RegisterType(TC.URI, minOccurs=0, nillable=False) TC.RegisterType(TC.Base64String, minOccurs=0, nillable=False) TC.RegisterType(TC.HexBinaryString, minOccurs=0, nillable=False) #TC.RegisterType(TC.Integer) #TC.RegisterType(TC.Decimal) for pyclass in ( TC.IunsignedByte, TC.IunsignedShort, TC.IunsignedInt, TC.IunsignedLong, TC.Ibyte, TC.Ishort, TC.Iint, TC.Ilong,
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)
#! /usr/bin/env python # $Header$ '''Simple CGI dispatching. ''' from pysphere.ZSI import TC import base64, os from pysphere.ZSI import ZSI_SCHEMA_URI _b64_decode = base64.decodestring # Typecode to parse a ZSI BasicAuth header. _auth_tc = TC.Struct(None, [ TC.String('Name'), TC.String('Password') ], extras=1) class AUTH: '''Constants for authentication mechanisms. ''' none = 0 httpbasic = 1 zsibasic = 2 httpdigest = 4 class ClientBinding: '''Information about the client that is connected to us. ''' def __init__(self, ps): self.ps, self.auth = \
def call_closure(*args, **kwargs): """Call the named remote web service method.""" if len(args) and len(kwargs): raise TypeError('Use positional or keyword argument only.') if len(args) > 0: raise TypeError('Not supporting SOAPENC:Arrays or XSD:List') if len(kwargs): args = kwargs callinfo = getattr(self, name).callinfo # go through the list of defined methods, and look for the one with # the same number of arguments as what was passed. this is a weak # check that should probably be improved in the future to check the # types of the arguments to allow for polymorphism for method in self._methods[name]: if len(method.callinfo.inparams) == len(kwargs): callinfo = method.callinfo binding = _Binding(url=self._url or callinfo.location, soapaction=callinfo.soapAction, **self._kw) kw = dict(unique=True) if callinfo.use == 'encoded': kw['unique'] = False if callinfo.style == 'rpc': request = TC.Struct(None, ofwhat=[], pname=(callinfo.namespace, name), **kw) response = TC.Struct(None, ofwhat=[], pname=(callinfo.namespace, name+"Response"), **kw) if len(callinfo.getInParameters()) != len(args): raise RuntimeError('expecting "%s" parts, got %s' %( str(callinfo.getInParameters(), str(args)))) for msg,pms in ((request,callinfo.getInParameters()), (response,callinfo.getOutParameters())): msg.ofwhat = [] for part in pms: klass = GTD(*part.type) if klass is None: if part.type: klass = [gt for gt in TC.TYPES if part.type==gt.type] if len(klass) == 0: klass = [gt for gt in TC.TYPES if part.type[1]==gt.type[1]] if not len(klass):klass = [TC.Any] if len(klass) > 1: #Enumerations, XMLString, etc klass = [i for i in klass if 'type' in i.__dict__] klass = klass[0] else: klass = TC.Any msg.ofwhat.append(klass(part.name)) msg.ofwhat = tuple(msg.ofwhat) if not args: args = {} else: # Grab <part element> attribute ipart,opart = callinfo.getInParameters(),callinfo.getOutParameters() if ( len(ipart) != 1 or not ipart[0].element_type or ipart[0].type is None ): raise RuntimeError('Bad Input Message "%s"' %callinfo.name) if ( len(opart) not in (0,1) or not opart[0].element_type or opart[0].type is None ): raise RuntimeError('Bad Output Message "%s"' %callinfo.name) # if ( len(args) > 1 ): # raise RuntimeError, 'Message has only one part: %s' %str(args) ipart = ipart[0] request,response = GED(*ipart.type),None if opart: response = GED(*opart[0].type) msg = args if self._asdict: if not msg: msg = dict() self._nullpyclass(request) elif request.pyclass is not None: if type(args) is dict: msg = request.pyclass() msg.__dict__.update(args) elif type(args) is list and len(args) == 1: msg = request.pyclass(args[0]) else: msg = request.pyclass() binding.Send(None, None, msg, requesttypecode=request, soapheaders=soapheaders, encodingStyle=callinfo.encodingStyle) if response is None: return None if self._asdict: self._nullpyclass(response) return binding.Receive(replytype=response, encodingStyle=callinfo.encodingStyle)
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)
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 callable(h)] 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, ex: SendFault(FaultFromZSIException(ex), **kw) return try: result = handler(arg) except Exception, ex: SendFault(FaultFromZSIException(ex), **kw) return try: tc = result.typecode except AttributeError, ex: SendFault(FaultFromZSIException(ex), **kw) return
SendFault(FaultFromZSIException(ex), **kw) return try: tc = result.typecode except AttributeError, 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, 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):