def do_POST(self): '''The POST command. This is called by HTTPServer, not twisted. action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header) ''' global _contexts soapAction = self.headers.getheader('SOAPAction') post = self.path if not post: raise PostNotSpecified, 'HTTP POST not specified in request' if soapAction: soapAction = soapAction.strip('\'"') post = post.strip('\'"') try: ct = self.headers['content-type'] if ct.startswith('multipart/'): cid = resolvers.MIMEResolver(ct, self.rfile) xml = cid.GetSOAPPart() ps = ParsedSoap(xml, resolver=cid.Resolve, readerclass=DomletteReader) else: length = int(self.headers['content-length']) ps = ParsedSoap(self.rfile.read(length), readerclass=DomletteReader) except ParseException, e: self.send_fault(FaultFromZSIException(e))
def do_POST(self): '''The POST command. This is called by HTTPServer, not twisted. action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header) ''' global _contexts soapAction = self.headers.getheader('SOAPAction') post = self.path if not post: raise PostNotSpecified('HTTP POST not specified in request') if soapAction: soapAction = soapAction.strip('\'"') post = post.strip('\'"') try: ct = self.headers['content-type'] if ct.startswith('multipart/'): cid = resolvers.MIMEResolver(ct, self.rfile) xml = cid.GetSOAPPart() ps = ParsedSoap(xml, resolver=cid.Resolve, readerclass=DomletteReader) else: length = int(self.headers['content-length']) ps = ParsedSoap(self.rfile.read(length), readerclass=DomletteReader) except ParseException as e: self.send_fault(FaultFromZSIException(e)) except Exception as e: # Faulted while processing; assume it's in the header. self.send_fault(FaultFromException(e, 1, sys.exc_info()[2])) else: # Keep track of calls thread_id = _thread.get_ident() _contexts[thread_id] = SOAPContext(self.server, xml, ps, self.connection, self.headers, soapAction) try: _Dispatch(ps, self.server, self.send_xml, self.send_fault, post=post, action=soapAction) except Exception as e: self.send_fault(FaultFromException(e, 0, sys.exc_info()[2])) # Clean up after the call if thread_id in _contexts: del _contexts[thread_id]
def AsCGI(nsdict={}, typesmodule=None, rpc=False, modules=None): '''Dispatch within a CGI script. ''' if os.environ.get('REQUEST_METHOD') != 'POST': _CGISendFault(Fault(Fault.Client, 'Must use POST')) return ct = os.environ['CONTENT_TYPE'] try: if ct.startswith('multipart/'): cid = resolvers.MIMEResolver(ct, sys.stdin) xml = cid.GetSOAPPart() ps = ParsedSoap(xml, resolver=cid.Resolve) else: length = int(os.environ['CONTENT_LENGTH']) ps = ParsedSoap(sys.stdin.read(length)) except ParseException as e: _CGISendFault(FaultFromZSIException(e)) return _Dispatch(ps, modules, _CGISendXML, _CGISendFault, nsdict=nsdict, typesmodule=typesmodule, rpc=rpc)
def AsJonPy(request=None, modules=None, **kw): '''Dispatch within a jonpy CGI/FastCGI script. ''' kw['request'] = request if request.environ.get('REQUEST_METHOD') != 'POST': _JonPySendFault(Fault(Fault.Client, 'Must use POST'), **kw) return ct = request.environ['CONTENT_TYPE'] try: if ct.startswith('multipart/'): cid = resolvers.MIMEResolver(ct, request.stdin) xml = cid.GetSOAPPart() ps = ParsedSoap(xml, resolver=cid.Resolve) else: length = int(request.environ['CONTENT_LENGTH']) ps = ParsedSoap(request.stdin.read(length)) except ParseException as e: _JonPySendFault(FaultFromZSIException(e), **kw) return _Dispatch(ps, modules, _JonPySendXML, _JonPySendFault, **kw)
def do_POST(self): '''The POST command. action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header) ''' self._fix_chunked_encoding() logger.debug("Request Host: {}".format(self.client_address)) logger.debug("Request URI: {}".format(self.requestline)) for key, value in self.headers.items(): logger.debug("Request Header: {}: {}".format(key, value)) content_type = self.headers.get("content-type", '') action_matchobj = re.search("action=\"(urn:\w+)\"", content_type) if action_matchobj is not None: # SOAP 1.2 soapAction = action_matchobj.group(1) else: # SOAP 1.1 soapAction = self.headers.getheader('SOAPAction') if soapAction: soapAction = soapAction.strip('\'"') self._soapAction = soapAction post = self.path if not post: raise PostNotSpecified, 'HTTP POST not specified in request' post = post.strip('\'"') try: ct = self.headers['content-type'] if ct.startswith('multipart/'): cid = resolvers.MIMEResolver(ct, self.rfile) xml = cid.GetSOAPPart() ps = ParsedSoap(xml, resolver=cid.Resolve) else: length = int(self.headers['content-length']) xml = self.rfile.read(length) logger.debug("Request Body: {}".format(xml)) ps = ParsedSoap(xml) except ParseException, e: self.send_fault(FaultFromZSIException(e))
def do_POST(self): '''The POST command. ''' try: ct = self.headers['content-type'] if ct.startswith('multipart/'): cid = resolvers.MIMEResolver(ct, self.rfile) xml = cid.GetSOAPPart() ps = ParsedSoap(xml, resolver=cid.Resolve) else: length = int(self.headers['content-length']) ps = ParsedSoap(self.rfile.read(length)) except ParseException as e: self.send_fault(FaultFromZSIException(e)) return except Exception as e: # Faulted while processing; assume it's in the header. self.send_fault(FaultFromException(e, 1, sys.exc_info()[2])) return _Dispatch(ps, self.server.modules, self.send_xml, self.send_fault, docstyle=self.server.docstyle, nsdict=self.server.nsdict, typesmodule=self.server.typesmodule, rpc=self.server.rpc)
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 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 checkt2(self): try: ps = ParsedSoap(IN) except ParseException, e: print >> OUT, FaultFromZSIException(e).AsSOAP() self.fail()
# We are not prepared to handle any actors or mustUnderstand elements. # Arbitrary fault back with the first one found. a = ps.WhatActorsArePresent() if len(a): print >> OUT, FaultFromActor(a[0]).AsSOAP() self.fail() mu = ps.WhatMustIUnderstand() if len(mu): uri, localname = mu[0] print >> OUT, FaultFromNotUnderstood(uri, localname).AsSOAP() self.fail() try: player = ps.Parse(Player) except EvaluateException, e: print >> OUT, FaultFromZSIException(e).AsSOAP() self.fail() try: import operator total = reduce(operator.add, player.Scores, 0) result = Average(foo(total, len(player.Scores))) sw = SoapWriter().serialize(result) str(sw) #print >>OUT, str(sw) except Exception, e: print >> OUT, FaultFromException(e, 0, sys.exc_info()[2]).AsSOAP() self.fail() def makeTestSuite():