/usr/share/pyshared/ZSI/twisted/wsgi.py is in python-zsi 2.1~a1-3build1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | ############################################################################
# Joshua R. Boverhof, LBNL
# See Copyright for copyright notice!
# $Id: $
###########################################################################
import os, sys, types, inspect
from StringIO import StringIO
# twisted & related imports
from zope.interface import classProvides, implements, Interface
# ZSI imports
from ZSI import _get_element_nsuri_name, EvaluateException, ParseException,\
fault, ParsedSoap, SoapWriter
from ZSI.twisted.reverse import DataHandler, ReverseHandlerChain,\
HandlerChainInterface
"""
EXAMPLES:
See zsi/samples/WSGI
"""
def soapmethod(requesttypecode, responsetypecode, soapaction='',
operation=None, **kw):
"""@soapmethod
decorator function for soap methods
"""
def _closure(func_cb):
func_cb.root = (requesttypecode.nspname,requesttypecode.pname)
func_cb.action = soapaction
func_cb.requesttypecode = requesttypecode
func_cb.responsetypecode = responsetypecode
func_cb.soapmethod = True
func_cb.operation = None
return func_cb
return _closure
class SOAPCallbackHandler:
""" ps --> pyobj, pyobj --> sw
class variables:
writerClass -- ElementProxy implementation to use for SoapWriter instances.
"""
classProvides(HandlerChainInterface)
writerClass = None
@classmethod
def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resource']
request = kw['request']
root = _get_element_nsuri_name(ps.body_root)
for key,method in inspect.getmembers(resource, inspect.ismethod):
if (getattr(method, 'soapmethod', False) and method.root == root):
break
else:
raise RuntimeError, 'Missing soap callback method for root "%s"' %root
try:
req = ps.Parse(method.requesttypecode)
except Exception, ex:
raise
try:
rsp = method.responsetypecode.pyclass()
except Exception, ex:
raise
try:
req,rsp = method(req, rsp)
except Exception, ex:
raise
return rsp
@classmethod
def processResponse(cls, output, **kw):
sw = SoapWriter(outputclass=cls.writerClass)
sw.serialize(output)
return sw
class SOAPHandlerChainFactory:
protocol = ReverseHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(DataHandler, SOAPCallbackHandler)
class WSGIApplication(dict):
encoding = "UTF-8"
def __call__(self, env, start_response):
"""do dispatching, else process
"""
script = env['SCRIPT_NAME'] # consumed
ipath = os.path.split(env['PATH_INFO'])[1:]
for i in range(1, len(ipath)+1):
path = os.path.join(*ipath[:i])
print "PATH: ", path
application = self.get(path)
if application is not None:
env['SCRIPT_NAME'] = script + path
env['PATH_INFO'] = ''
print "SCRIPT: ", env['SCRIPT_NAME']
return application(env, start_response)
return self._request_cb(env, start_response)
def _request_cb(self, env, start_response):
"""callback method, override
"""
start_response("404 ERROR", [('Content-Type','text/plain')])
return ['Move along people, there is nothing to see to hear']
def putChild(self, path, resource):
"""
"""
path = path.split('/')
lp = len(path)
if lp == 0:
raise RuntimeError, 'bad path "%s"' %path
if lp == 1:
self[path[0]] = resource
for i in range(len(path)):
if not path[i]: continue
break
next = self.get(path[i], None)
if next is None:
next = self[path[i]] = WSGIApplication()
next.putChild('/'.join(path[-1:]), resource)
class SOAPApplication(WSGIApplication):
"""
"""
factory = SOAPHandlerChainFactory
def __init__(self, **kw):
dict.__init__(self, **kw)
self.delegate = None
def _request_cb(self, env, start_response):
"""process request,
"""
if env['REQUEST_METHOD'] == 'GET':
return self._handle_GET(env, start_response)
if env['REQUEST_METHOD'] == 'POST':
return self._handle_POST(env, start_response)
start_response("500 ERROR", [('Content-Type','text/plain')])
s = StringIO()
h = env.items(); h.sort()
for k,v in h:
print >>s, k,'=',`v`
return [s.getvalue()]
def _handle_GET(self, env, start_response):
if env['QUERY_STRING'].lower() == 'wsdl':
start_response("200 OK", [('Content-Type','text/plain')])
r = self.delegate or self
return _resourceToWSDL(r)
start_response("404 ERROR", [('Content-Type','text/plain')])
return ['NO RESOURCE FOR GET']
def _handle_POST(self, env, start_response):
"""Dispatch Method called by twisted render, creates a
request/response handler chain.
request -- twisted.web.server.Request
"""
input = env['wsgi.input']
data = input.read( int(env['CONTENT_LENGTH']) )
mimeType = "text/xml"
if self.encoding is not None:
mimeType = 'text/xml; charset="%s"' % self.encoding
request = None
resource = self.delegate or self
chain = self.factory.newInstance()
try:
pyobj = chain.processRequest(data, request=request, resource=resource)
except Exception, ex:
start_response("500 ERROR", [('Content-Type',mimeType)])
return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
try:
soap = chain.processResponse(pyobj, request=request, resource=resource)
except Exception, ex:
start_response("500 ERROR", [('Content-Type',mimeType)])
return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
start_response("200 OK", [('Content-Type',mimeType)])
return [soap]
def test(app, port=8080, host="localhost"):
"""
"""
from twisted.internet import reactor
from twisted.python import log
from twisted.web2.channel import HTTPFactory
from twisted.web2.server import Site
from twisted.web2.wsgi import WSGIResource
log.startLogging(sys.stdout)
reactor.listenTCP(port,
HTTPFactory( Site(WSGIResource(app)) ),
interface=host,
)
reactor.run()
def _issoapmethod(f):
return type(f) is types.MethodType and getattr(f, 'soapmethod', False)
def _resourceToWSDL(resource):
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, QName
from ZSI.wstools.Namespaces import WSDL
r = resource
methods = filter(_issoapmethod, map(lambda i: getattr(r, i), dir(r)))
tns = ''
#tree = ElementTree()
defs = Element("{%s}definitions" %WSDL.BASE)
defs.attrib['name'] = 'SampleDefs'
defs.attrib['targetNamespace'] = tns
#tree.append(defs)
porttype = Element("{%s}portType" %WSDL)
porttype.attrib['name'] = QName("{%s}SamplePortType" %tns)
binding = Element("{%s}binding" %WSDL)
defs.append(binding)
binding.attrib['name'] = QName("{%s}SampleBinding" %tns)
binding.attrib['type'] = porttype.get('name')
for m in methods:
m.action
service = Element("{%s}service" %WSDL.BASE)
defs.append(service)
service.attrib['name'] = 'SampleService'
port = Element("{%s}port" %WSDL.BASE)
service.append(port)
port.attrib['name'] = "SamplePort"
port.attrib['binding'] = binding.get('name')
soapaddress = Element("{%s}address" %WSDL.BIND_SOAP)
soapaddress.attrib['location'] = 'http://localhost/bla'
port.append(soapaddress)
return [ElementTree.tostring(defs)]
"""
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions name="Counter" targetNamespace="http://counter.com/bindings" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:porttype="http://counter.com" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<wsdl:import namespace="http://counter.com" location="counter_flattened.wsdl"/>
<wsdl:binding name="CounterPortTypeSOAPBinding" type="porttype:CounterPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="createCounter">
<soap:operation soapAction="http://counter.com/CounterPortType/createCounterRequest"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
<wsdl:definitions name="Counter" targetNamespace="http://counter.com/service"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:binding="http://counter.com/bindings">
<wsdl:import namespace="http://counter.com/bindings" location="counter_bindings.wsdl"/>
<wsdl:service name="CounterService">
<wsdl:port name="CounterPortTypePort" binding="binding:CounterPortTypeSOAPBinding">
<soap:address location="http://localhost:8080/wsrf/services/"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
"""
|