XML technologies / XML / Python & XML / Python and distributed systems design / The XML switch
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
The XML switch is the distributed system’s heart, mediating between information consumers and producers. It centers on two concepts:
Mediation between frontend applications and backend information systems.
A fundamental XML message structure providing flexibility between sender and recipient.
The XML architecture
The switch architecture is message- and RPC-based, mediating between frontends such as web servers or desktop applications and backends such as databases and remote services. Messages replace direct system wiring with an application-independent traffic pattern that can be managed separately.
Patching a CGI script that directly accesses a database requires a specific object understanding not just the connection but the schema and data types. With XML, your and other applications need know only an XML structure produced by the database upon receiving the right message. Any system needing to understand that message can do so today or years later. Such flexibility is valuable for distributed systems evolving over long periods.
This switch is a simple messaging prototype facilitating XML messages in distributed Python systems. Ideally, your message format should be SOAP or another format easily exchanged among emerging commercial systems. Space prevents developing a full SOAP messaging server and sample clients, so we use a simple XML format supporting similar RPC and messaging functions.
Core XML switch classes
The switch has three main components. First is XMLMessage. This class is the system’s basic unit. With its XML message structure, it underpins communication with neighboring applications. A client on any platform can create a message the switch understands; the format is essential to operation.
Equally important is XMLSwitch-Handler, implementing the HTTP handler intercepting server calls. The task of XMLSwitchHandler is to parse and execute RPC messages correctly and quickly send XML results back to callers.
Clients initiate every exchange between the switch and backend systems connected through objects. Clients use class xsc to send XML messages. Its black-box design makes messages disappear inside the switch and information reappear as XML!
XMLMessage
Defined in XMLMessage.py; see example XMLMessage.py. It encapsulates the standard message format for developers. A sample message (message.xml) appears in A sample message.xml file.
XMLSwitchHandler
Defined in XMLSwitchHandler.py; see XMLSwitchHandler.py later in this section. It starts the server accepting end-user XML messages and connecting them with backend resources. Results return to the originating application in another XML message.
xsc
This class provides a client API with a message-sending method. The method sendMessage takes a well-formed XML message string and sends it to the switch. If successful, the server invokes the method and parameters on an available object and returns the result.
The XMLMessage class
Systems exchange messages inside a simple XML envelope. This envelope resembles SOAP structurally. Because Python’s SOAP support is still emerging and space is limited, we use this simple structure, shown empty:
<message>
<header></header>
<body></body>
</message>With this organization, elements can contain anything XML tags permit: SOAP fragments, web pages, records and more.
The XMLMessage format
This example shows a complete well-formed message:
Example: A sample message.xml file
<message>
<header><rpc/></header>
<body>
<object class="CustomerProfile" method="getProfile">
<param>234-E838839</param>
</object>
</body>
</message>The format is a thin wrapper consisting of elements message, header and body. The example is an RPC call. The server first examines its header, identifies RPC, extracts the payload and invokes the appropriate object method with the parameters. It then modifies the XML message and sends it back through the switch.
The XMLMessage class
The class XMLMessage is easy to use. Create messages from XML strings or document objects, or load them from files. Accessors then provide quick access to parts. Methods getHeader and getBody extract header or body data. Methods setHeader and setBody modify messages before forwarding. The full message can switch between string and DOM object representations with methods getXMLMessage and setXMLMessage and their DOM counterparts getXMLMessageDom and setXMLMessageDom. The next short script demonstrates common loading and inspection methods using message.xml from the previous example.
Example: runxm.py — using an XMLMessage object
"""
runxm.py - führe XMLMessage-Objekt aus
"""
import XMLMessage
from xml.dom.ext import PrettyPrint
#from xml.dom.ext.reader.Sax2 import FromXml
xm = XMLMessage.XMLMessage( )
xm.loadXMLMessage("message.xml")
from xml.dom.ext import PrettyPrint
PrettyPrint(xm.getXMLMessageDom( ))
print "Ändern des Body zu: <body>Hallo!</body>"
if xm.setBody("<body>Hallo!</body>"):
print xm.getXMLMessage( )This code produces:
G:\pythonxml\c10>python runxm.py
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE message>
<message>
<header>
<rpc/>
</header>
<body>
<!-- cp.getProfile("234-E838839") -->
<object method='getProfile' class='CustomerProfile'>
<param>234-E838839</param>
</object>
</body>
</message>
Ändern des Body zu: <body>Hallo!</body>
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE message>
<message>
<header>
<rpc/>
</header>
<body>Hallo!</body>
</message>The output confirms successful loading and body modification. Methods of class XMLMessage are simple and mostly similar. Here is a brief reference to the methods of class XMLMessage:
setBody(strXML)
setBody takes an XML string representing a well-formed element body and replaces the message’s element body with the new content.
getBody( )
Returns the element body as an XML string, stored in self._body.
setHeader(strXML)
Replaces the existing element header with the given XML string.
getHeader( )
Returns the element header as a string, stored in self._header.
setXMLMessage(strXMLMessage)
Takes an XML message document as a string. The parameter becomes the entire message, whose new content is returned in later calls to getBody, getHeader and getXMLMessage.
setXMLMessageDom(xmldom)
Like setXMLMessage but takes a DOM object representing a well-formed message instead of a string.
loadXMLMessage(file)
Sets the current XML message’s content to that of file provided it is well-formed.
getXMLMessage( )
Returns the complete message as a string.
getXMLMessageDom( )
Returns the complete message as a DOM instance.
Implementing these methods uses much of our DOM knowledge so far, with a few noteworthy new techniques discussed next.
XML message code architecture
Most work in class XMLMessage happens in method setXMLMessage, which accepts a hidden DOM parameter specifying whether the new message is a string or a DOM instance.
The full document is created, then elements are populated by extracting the relevant names. This lets class XMLMessage provide accessors for the two most frequently used elements: header and body.
if dom:
self._dom = strXMLMessage
Holder = StringIO.StringIO( )
PrettyPrint(self._dom, Holder)
self._xml = Holder.getvalue( )
else:
dom = FromXml(strXMLMessage)
self._dom = dom
self._xml = strXMLMessage
# Header als String
Holder = StringIO.StringIO( )
PrettyPrint(self._dom.getElementsByTagName("header")[0],
Holder)
self._header = Holder.getvalue( )
# Body als String
Holder = StringIO.StringIO( )
PrettyPrint(self._dom.getElementsByTagName("body")[0],
Holder)
self._body = Holder.getvalue( ) Populating elements at the start of parsing stores their data as strings immediately available to callers. Replacing either element body or header reconstructs it, so to speak, and processes the document again as a string:
def setBody(self, strXML):
"""
setBody(strXML) - Das angegebene XML wird
für den Body der XML-Nachricht benutzt.
"""
xmlstr = FromXml(str("<message>" +
self._header + strXML + "</message>"))
return self.setXMLMessageDom(xmlstr)This shortcut reparses the whole document. Alternatively, parse it into nodes with read/write accessors, a more DOM-friendly approach requiring much more code.
XMLMessage code listing
The following example contains the full listing of XMLMessage.py.
Example: XMLMessage.py
"""
XMLMessage.py - eine Hülle für message.xml-Dokumente
"""
import StringIO
from xml.dom.ext import PrettyPrint
from xml.dom.ext.reader.Sax2 import FromXmlStream, FromXml
class XMLMessage:
"""
XMLMessage kapselt ein message.xml-Dokument vor den Benutzern der Klasse.
"""
def __init__(self):
self._dom = ""
self._xml = ""
def setBody(self, strXML):
"""
setBody(strXML) - Das angegebene XML wird
für den Body der XML-Nachricht benutzt.
"""
xmlstr = FromXml(str("<message>" +
self._header + strXML + "</message>"))
return self.setXMLMessageDom(xmlstr)
def getBody(self):
""" Liefert Body als String
"""
return self._body
def setHeader(self, strXML):
"""
setHeader(strXML) - Das angegebene XML
wird als Header der XML-Nachricht benutzt.
"""
xmlstr = FromXml(str("<message>" + strXML + self._body + "</message>"))
return self.setXMLMessageDom(xmlstr)
def getHeader(self):
""" Liefert Header als String
"""
return self._header
def setXMLMessage(self, strXMLMessage, dom=0):
"""
setXMLMessage - benutzt XML als gesamte
XML-Nachricht
"""
try:
if dom:
# Weise dom direkt mit Parameter zu
self._dom = strXMLMessage
# Fülle StringIO-Objekt für self._xml
Holder = StringIO.StringIO()
PrettyPrint(self._dom, Holder)
# Weise String-Wert von dom an self._xml zu
self._xml = Holder.getvalue()
else:
# Erzeuge dom aus angegebenem XML-String
dom = FromXml(strXMLMessage)
# Setze dom als Objektattribut
self._dom = dom
# Setze XML-String als Objektattribut
self._xml = strXMLMessage
# Header als DOM
self._headerdom = self._dom.getElementsByTagName("header")[0]
# Header als String
Holder = StringIO.StringIO()
PrettyPrint(self._dom.getElementsByTagName("header")[0],
Holder)
self._header = Holder.getvalue()
# Body als DOM
self._bodydom = self._dom.getElementsByTagName("body")[0]
# Body als String
Holder = StringIO.StringIO()
PrettyPrint(self._dom.getElementsByTagName("body")[0],
Holder)
self._body = Holder.getvalue()
except:
print "DOM konnte nicht aus der Nachricht erzeugt werden!"
return 0
return 1
def setXMLMessageDom(self, xmldom):
""" rufe setXMLMessage mit dom-Schalter auf
"""
return self.setXMLMessage(xmldom, dom=1)
def loadXMLMessage(self, file):
"""
loadXMLMessage - erstelle eine XML-Nachricht aus einer Datei oder URL
"""
try:
dom = FromXmlStream(file)
except:
print "XML-Nachricht konnte nicht geladen werden."
return 0
return self.setXMLMessageDom(dom)
def getXMLMessage(self, dom=0):
"""
getXMLMessage - liefert gesamte Nachricht entweder als XML-String oder DOM
"""
if dom:
return self._dom
else:
return self._xml
def getXMLMessageDom(self):
""" Liefert XML-Nachricht als DOM
"""
return self.getXMLMessage(dom=1) The class XMLMessage encapsulates a simple format with accessors for developers. The same approach can wrap more complex messages such as SOAP, letting you build SOAP-speaking components or begin migrating your distributed integration project to SOAP and Python.
The XML switch service
The switch combines a server process and client API for exposing object methods and properties over the web. XML messages invoke methods like SOAP calls. Because Python’s SOAP support is limited and space is short, we use the simple format described above. Messages marked by an element rpc in the header invoke object methods and return results in another XML message.
The service is largely provided by class XMLSwitchHandler developed later in XMLSwitchHandler.py. The clients developed later create and forward XML messages. The server checks for RPC calls, loads the appropriate object, executes the method, wraps the result in XML and returns it.
A lookup table could apply routing rules to incoming messages. One switch could also route to another, letting messages hop toward their destination and decoupling sender from recipient. Chained switches form a scalable, routable XML network.
The XML switch client
There are two principal clients. The first, postMsg.html, is a web page posting data to the right server and URL. The reply is raw XML, displayed as a tree by Internet Explorer, handled by a content handler in Netscape, or shown as plain text.
The XML switch client is a Python API also usable from the command line. One method sends messages and receives responses. We examine clients first, then build the server.
Using postMsg.html to return XML
The file postMsg.html sends data to the server and invokes method echoReponse to test functionality. It appears in the following example.
Example: The postMsg.html file
<html>
<body>
<form action="http://centauri:2112/" method="POST">
<p>Eingabe hier:</p>
<p>
<textarea name="n" rows=20 cols=80>
<message>
<header><non-rpc/></header>
<body><!-- cp.getProfile("234-E838839") -->
<object class="CustomerProfile" method="getProfile">
<param>234-E838839</param>
</object>
</body>
</message>
</textarea>
</p>
<p><input type="submit" value="Daten Abschicken"></p>
</form>
</body>
</html>The method echoResponse is ideal for testing. Using the file postMsg.html from the previous example sends a sample message and receives a reply, as shown below.
Figure: Connecting with postMsg.html
With a message header containing <rpc/> instead of <non-rpc/>, however, the XML response is generated by executing the RPC on the server.
For example, enter this XML in postMsg.html:
<message>
<header><rpc/></header>
<body>
<object class="CustomerProfile" method="getProfile">
<param>983-E2229J3</param>
</object>
</body>
</message>and click submit data to receive the raw XML package. Internet Explorer displays it with its default stylesheet, as below. This requires a profile with ID 983-E2229J3 in the database; otherwise replace the ID with an existing one.
Figure: Making an RPC call with postMsg.html
In fact, postMsg.html should handle any valid message sent to the server. To demonstrate the API directly, run the xsc client from the command line or Python code.
Using the XSC client
The xsc.py, the XML switch client example shows the xsc client xsc.py, which calls the switch and inspects returned messages. For command-line use, xsc requires messages in a local file.
The XML file is a simple message document. This example shows msgGetProfile.xml, a sample message usable with xsc.
Example: msgGetProfile.xml
<message>
<header><rpc/></header>
<body>
<object class="CustomerProfile" method="getProfile">
<param>983-E2229J3</param>
</object>
</body>
</message>Run the file with the message filename as its argument:
Example: Running xcs.py from the command line
G:\pythonxml\c10> python xsc.py msgGetProfile.xml
XMLSwitch-Server: localhost:2112
[200 OK 522 bytes]
Antwort:
<message>
<header>
<rpc-response/>
</header>
<body>
<object method='getProfile' class='CustomerProfile'>
<response>
<CustomerProfile id='983-E2229J3'>
<firstname>Larry</firstname>
<lastname>BoBerry</lastname>
<address1>Northpoint Apartments</address1>
<address2>Apt. 2087</address2>
<city>Lemmonville</city>
<state>MD</state>
<zip>12345</zip>
</CustomerProfile>
</response>
</object>
</body>
</message>The xsc command-line operation prints the server, HTTP response code and message, and XML document size, followed by the returned XML.
Using the XSC API
Programs can also call the switch. Later clients communicate with other systems through the xsc client and small XML rpc messages.
To use the xsc API, import xsc into your class.
import sys
import xsc
xc = xsc.xsc( )Next specify the server/port pair where the switch runs:
xc.server = "localhost:2112" You also need XML to send; loading a message from a file is convenient.
fd = open(sys.argv[1], "r")
xmlmsg = fd.read( )
fd.close( )Finally, a single method call sends the message and receives the result:
response = xc.sendMessage(xmlmsg)
print responseThat is enough to invoke remote Python objects querying SQL databases and XML stores. The switch mediates, receiving XML requests and returning XML information.
The complete code of xsc.py, used both for command-line requests and programmatic access, appears next.
Example: xsc.py, the XML switch client
"""
xsc.py - XMLSwitch-Client
Benutzung: python xsc.py meineAnfrageDatei.xml
"""
import sys
import httplib
from urllib import quote_plus
class xsc:
"""
xsc - XMLSwitch-Client
Diese Klasse ist sowohl die Kommandozeilen- als auch
die Modulschnittstelle zu XMLSwitch.
Von der Kommandozeile:
$> python xsc.py msgDatei.xml
Der dritte Parameter ist eine XML-Datei mit einer gültigen <message> darin.
Die Antwort-<message> wird auf die Konsole geschrieben werden.
Als API:
import xsc
responseXML = xsc.sendMessage(strXMLMessage)
Das Ergebnis ist nun in responseXML.
"""
def __init__(self):
"""
init - setze einige öffentliche Attribute
"""
self.server = "localhost:2112" # host:port (80 ist http)
self.stats = ""
def sendMessage(self, strXMLMessage):
"""
sendMessage(strXML) - diese Methode sendet die
angegebene XML-Nachricht an den Server in self.server.
Die XML-Antwort wird an den Aufrufer zurückgegeben.
"""
# Bereite XML-Nachricht durch Codieren der URL vor...
strXMLRequest = quote_plus(strXMLMessage)
# Verbinde mit Server...
req = httplib.HTTP(self.server)
# Füge HTTP-Header hinzu, inkl. content-length
# als Größe unserer XML-Nachricht
req.putrequest("POST", "/")
req.putheader("Accept", "text/html")
req.putheader("Accept", "text/xml")
req.putheader("User-Agent", "xsc.py")
req.putheader("Content-length", str(len("n=" + strXMLRequest)))
req.endheaders()
# Sende XML als POST-Daten
req.send("n=" + strXMLRequest)
# Empfange HTTP-Antwort
ec, em, h = req.getreply()
# content-length gibt Anzahl von Bytes in der XML-Antwortnachricht an
cl = h.get("content-length", "0")
# Status [http-code, http-msg, content-length]
self.stats = ("[" + str(ec) + " " +
str(em) + " " +
str(cl) + " bytes]")
# Versuche XML-Antwort zu lesen
nfd = req.getfile()
try:
textlines = nfd.read()
nfd.close()
# Gib XML-Daten zurück
return textlines
except:
# Beende nach Ausnahme
nfd.close()
return ""
# Kommandozeilen-Betrieb
if __name__ == "__main__":
# Instanziiere Server
xc = xsc()
xc.server = "localhost:2112"
# Lies Nachrichtendatei
fd = open(sys.argv[1], "r")
xmlmsg = fd.read()
fd.close()
# Rufe Server auf und gib Status und Antwort aus
print "XMLSwitch-Server: ", xc.server
response = xc.sendMessage(xmlmsg)
print xc.stats
print "Antwort: "
print responseThe XMLSwitchHandler server class
The class XMLSwitchHandler is a BaseHTTPRequestHandler. The full class XMLSwitch-Handler appears in XMLSwitchHandler.py. The additional script runxs.py starts the server from the command line. It appears in XML switch startup script: runxs.py.
XMLSwitchHandler code architecture
The architecture behind XMLSwitchHandler uses considerable XML. The key method is processXMLMessagePost, the real workhorse. Messages arrive URL-encoded. Decode them to understand the client’s request, then try to obtain a DOM-friendly XMLMessage object from the result:
def processXMLMessagePost(self, strPostData):
"""
processXMLMessagePost(strXMLMessage) - diese Methode erzeugt eine
XMLMessage aus den angegebenen Daten und sucht nach einer Abbildung
in XMLMapping.xml, um zu bestimmen, welches Objekt/Methode-Paar
aufzurufen ist.
"""
# Erzeuge Nachricht durch Decodieren der post-Daten
xmsg = XMLMessage( )
xmsg.setXMLMessage(
unquote_plus(strPostData).replace("n=", ""))At this point, xmsg is a new XMLMessage object encapsulating the client request. Now inspect the header. If its text is <rpc/>, the server treats the message as an rpc call. Otherwise it is treated as non-rpc and sent to method echoResponse which uses HTML to return it to the client.
# Teste Header auf Element <rpc/>
strHeader = xmsg.getHeader( )
if strHeader.rfind("<rpc/>") < 0:
# Sende ein HTML-Echo zurück
self.echoResponse(strPostData)
return 0For an RPC candidate, extract object and method names and parameters. This is not entirely straightforward:
# Werte object.method(params) aus
msgDom = xmsg.getXMLMessageDom( )
objElem = msgDom.getElementsByTagName("object")[0]
object = objElem.getAttributeNS('',"class")
method = objElem.getAttributeNS('',"method")
params = []
paramElems = msgDom.getElementsByTagName("param")
# Hole Parameter als Strings
for thisparam in paramElems:
strParam = StringIO.StringIO( )
PrettyPrint(thisparam, strParam)
parameter = strParam.getvalue().strip( )
parameter = parameter.replace("<param>", "")
parameter = parameter.replace("</param>", "")
params.append(parameter)After extracting the required data, prepare a command string containing the local object instance, method name and parameters:
# Instanziiere korrektes Objekt
if object == "CustomerProfile":
from CustomerProfile import CustomerProfile
inst = CustomerProfile( )
if object == "XMLOffer":
from XMLOffer import XMLOffer
inst = XMLOffer( )
# '''''''''''''''''''''''''''''''''''''''''''''''''''''
# Fügen Sie hier weitere Objekt-Instanziierungen hinzu
# '''''''''''''''''''''''''''''''''''''''''''''''''''''
# Bereite cmd-String vor
cmd = "inst." + method + "("
# Füge Parameter an Kommando hinzu, wenn nötig,
# getrennt durch """ und Kommas
if len(params) == 1:
cmd += '"""' + params[0] + '""")'
elif len(params) > 1:
for pmIndex in range(len(params) - 1):
cmd += '"""' + params[pmIndex] + '""", '
cmd += '"""' + params[len(params)-1] + '""")'
# Ohne Parameter schließe einfach die Klammern: ( )
if not params:
cmd += ")"
This code carefully uses DOM to extract command values, combining them in a single cmd string. The highlighted lines show where the value of cmd changes to complete the command. Previous calls using msgGetProfile.xml would have been translated by XMLSwitchHandler to look like this:
inst.getProfile("983-E2229J3") Triple quotes escape existing single or double quotes in parameters. Naturally, triple quotes within an argument break this approach!
With methods prepared, use Python statement eval to invoke objects and methods:
result = eval(cmd) After invocation, use the result to create an XML response. A temporary DOM holds the new values, then is serialized to the client socket. While in DOM form, it can be validated or modified, for example to remove a prolog or information interfering with embedding in another document.
The XMLSwitchHandler script
The following example contains the complete listing of XMLSwitchHandler.py:
Example: XMLSwitchHandler.py
"""
XMLSwitchHandler.py
"""
import sys
import BaseHTTPServer
import StringIO
from urllib import unquote_plus
from XMLMessage import XMLMessage
from xml.dom.ext import PrettyPrint
from xml.dom.ext.reader.Sax2 import FromXml
class XMLSwitchHandler(
BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
"""
do_GET verarbeitet HTTP-GET-Anfragen auf dem Server-Port.
"""
# Sende generische HTML-Antwort
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("<html><body>")
self.wfile.write("<font face=tahoma size=2>")
self.wfile.write("<b>Hallo vom XMLSwitchHandler!</b>")
self.wfile.write("</font></body></html>")
def do_POST(self):
"""
do_POST verarbeitet HTTP-POST-Anfragen und XML-Pakete.
"""
if self.headers.dict.has_key("content-length"):
# Konvertiere content-length von String nach Ganzzahl
content_length = int(self.headers.dict["content-length"])
# Lies korrekte Anzahl von Bytes vom Client
# und verarbeite die Daten
raw_post_data = self.rfile.read(content_length)
self.processXMLMessagePost(raw_post_data)
return 1
else:
# fehlerhafte post-Operation
self.send_reponse(500)
return 0
def processXMLMessagePost(self, strPostData):
"""
processXMLMessagePost(strXMLMessage) - diese Methode erzeugt eine
XMLMessage aus den angegebenen Daten und sucht nach einer Abbildung
in XMLMapping.xml, um zu bestimmen, welches Objekt/Methode-Paar
aufzurufen ist.
"""
# Erzeuge Nachricht durch Decodieren der post-Daten
xmsg = XMLMessage()
xmsg.setXMLMessage(
unquote_plus(strPostData).replace("n=", ""))
# Teste Header auf Element <rpc/>
strHeader = xmsg.getHeader()
if strHeader.rfind("<rpc/>") < 0:
# Sende ein HTML-Echo zurück
self.echoResponse(strPostData)
return 0
# Werte object.method(params) aus
msgDom = xmsg.getXMLMessageDom()
objElem = msgDom.getElementsByTagName("object")[0]
object = objElem.getAttributeNS('',"class")
method = objElem.getAttributeNS('',"method")
params = []
paramElems = msgDom.getElementsByTagName("param")
# Hole Parameter als Strings
for thisparam in paramElems:
strParam = StringIO.StringIO()
PrettyPrint(thisparam, strParam)
parameter = strParam.getvalue().strip()
parameter = parameter.replace("<param>", "")
parameter = parameter.replace("</param>", "")
params.append(parameter)
# Instanziiere korrektes Objekt
if object == "CustomerProfile":
from CustomerProfile import CustomerProfile
inst = CustomerProfile()
if object == "XMLOffer":
from XMLOffer import XMLOffer
inst = XMLOffer()
# '''''''''''''''''''''''''''''''''''''''''''''''''''''
# Fügen Sie hier weitere Objekt-Instanziierungen hinzu
# '''''''''''''''''''''''''''''''''''''''''''''''''''''
# Bereite cmd-String vor
cmd = "inst." + method + "("
# Füge Parameter an Kommando hinzu, wenn nötig,
# getrennt durch """ und Kommas
if len(params) == 1:
cmd += "\"\"\"" + params[0] + "\"\"\"" + ")"
elif(len(params) > 1):
for pmIndex in range(0, (len(params) - 1)):
cmd += "\"\"\"" + params[pmIndex] + "\"\"\"" + ", "
cmd += "\"\"\"" + params[len(params)-1] + "\"\"\")"
# Ohne Parameter schließe einfach die Klammern: ()
if not params:
cmd += ")"
# Führe Kommando aus und halte Ergebnis fest
rezult = eval(cmd)
# Baue XML-Antwort
returnDom = FromXml(
"<message>\n\t<header>\n\t\t<rpc-response/>\n\t</header>\n" +
"\t<body>\n\t\t<object class=\"" + str(object) + "\" method=\"" +
str(method) + "\">\n\n\t\t\t<response>" + str(rezult) +
"</response>\n\t\t</object>\n\t</body>\n</message>\n")
# optional: validiere gegen Ergebnis-DOM oder
# irgendeine andere spezielle Logik
# Bereite String des Dokumentelements vor
# (schneide Prolog für die XML-Nachricht heraus)
strReturnXml = StringIO.StringIO()
PrettyPrint(returnDom.documentElement, strReturnXml)
xmlval = strReturnXml.getvalue()
# Gib XML über HTTP an Aufrufer zurück
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.send_header("Content-length", str(len(xmlval)))
self.end_headers()
self.wfile.write(str(xmlval))
return 1
def echoResponse(self, strPostData):
"""
echoResponse(postData) - gibt die in Header und Body geparsten post-Daten zurück.
"""
# Sende Antwort
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# Sende HTML-Text
self.wfile.write("<html><body>"
"<font color=blue face=tahoma size=5>"
"<b>Hallo vom XMLSwitchHandler!</b></font><br><br>"
"<font face=arial,verdana,helvetica size=4>"
"Versuche, eine XML-Nachricht "
"zu erstellen...<br><br>Kopf:<br><xmp>")
msg = XMLMessage()
msg.setXMLMessage(unquote_plus(strPostData).replace("n=", ""))
# Parse Nachricht in Header und Body, zeige als Beispiel auf Webseite an
self.wfile.write(msg.getHeader())
self.wfile.write("</xmp></font><font face=arial,verdana,helvetica"
" size='4'>Rumpf:<br><xmp>")
self.wfile.write(msg.getBody())
self.wfile.write("</xmp></font></body></html>")
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Python & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de