XML technologies / XML / Python & XML / Python and distributed systems design / A web application
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
Here you develop a website integrated with the XML switch and other network systems, even if all run on one machine. Users navigate server HTML to log in, retrieve their profiles, edit them or view special offers. A CGI script called by forms and other mechanisms retrieves information alongside the HTML.
Websites and CGI scripts normally query databases directly. This application differs: its CGI script uses the previously developed xsc client to communicate with the XML switch. Instead of SQL, it sends XML messages, which the switch maps to objects and appropriate methods to insert or retrieve information. Returned XML is parsed, formatted as HTML and shown to the user.
Connecting to a web service
Many web services can initially follow this model. Microsoft’s announced HailStorm services should let independent companies build websites retrieving users’ HailStorm calendars through SOAP calls from a web server or client to Microsoft. Your site formats and even brands the XML with your logo before returning it to the browser. This application follows the same bridged-services scenario, apart from important security and error-handling considerations.
The following diagram focuses on the website’s relationship with the XML switch and the rest of the network.
Figure: A web application detail
The figure does not show, and perhaps should not, the switch’s connections to other network resources. For CGI and HTML it is a black box supplying requested data.
Components
This standalone web/CGI application is fully integrated with our XML switching network. An HTML page and a server-side Python script generate dynamic data. CGI uses the switch client to retrieve information from the switch and backends. The website knows nothing of profiles in SQL Server or offers in a large flat file. It merely formats XML messages and expects the switch to return the right information.
We ran the HTML and CGI scripts on a five-line CGI server written in Python. Having used Apache and IIS elsewhere, we sought cross-platform simplicity here with a basic Python CGIHTTPServer. The HTML page intro.html and CGI script sp.py should run on any CGI-capable web server.
We develop these components:
intro.html
A simple login page taking a user ID and passing it to sp.py. It requires an ID valid in the database connected to the switch, corresponding to a record created earlier under Creating the database.
sp.py
A Python CGI script retrieving and formatting switch data. Its name does not end in .cgi, but rename it if your server executes only .cgi files. This workhorse receives data, formats it in HTML and returns it to the browser.
Place these files on the web server with sp.py in a directory named cgi-bin beneath intro.html. The form in intro.html and sp.py expect the file sp.py at /cgi-bin/sp.py.
Also copy xsc.py and XMLMessage.py into the directory cgi-bin so that sp.py can import them as modules.
Topology
As shown in A web application detail, CGI mainly transacts with a browser. For dynamic information, it uses the switch client to communicate across the network. This has broad network implications: intro.html and sp.py are requested from your web server; the script sp.py uses the switch client (xsc, developed in the example xsc.py, the XML switch client) to connect back to wherever the switch server runs. If the CGI script tells the client where to find it, the client gets what it needs. The end user’s browser only needs the website address.
We next highlight XML-focused code and present complete listings of the three main files.
Code architecture
The first step in building a website is a home page, here intro.html. The file intro.html politely asks for an ID. The login button sends it to the server; CGI returns formatted information in another dynamically generated HTML page. The following figure shows intro.html in a browser.
Figure: intro.html is the CGI example’s home page
As the figure shows, intro.html is very simple. The hardest part may be finding a valid profile ID. The following example shows intro.html.
Example: intro.html
<HTML>
<HEAD>
<TITLE>Einkauf-Portal von Super-Billig GmbH</TITLE>
</HEAD>
<BODY>
<P align="center"><h1>Einkauf-Portal von Super-Billig GmbH</h1></P>
<P>Hallo, wenn Sie noch nicht angemeldet sind, nehmen Sie sich bitte eine Minute dafür Zeit. Diese Site ist personalisiert, und Ihre persönlichen Informationen werden zusammen mit Sonderangeboten dank unserer mit Python erstellten, XML verarbeitenden Infrastruktur angeboten. Diese Website verteilt kleine XML-Nachrichten an und von einem XML-Switch. Dieser Switch leitet die XML-Nachrichten an die richtige Stelle, schickt die Nachrichten an einen Handler und gibt dann das XML an diese Website zurück. Das XML kann Ihnen dann in Form von Profil-Informationen und Sonderangeboten angezeigt werden.</P>
<P><h1>Willkommen</h1>
<form name=login action="/cgi-bin/sp.py" method="GET">Bitte geben Sie eine gültige Kunden-ID an* <br><input type="text" size="15" name="id"> <input type=submit value="Anmelden"><input type="hidden" name="mode" value="login"></form>
</P>
<P>*Diese ID muß in Ihrer Profil-Datenbank existieren!</P>
</BODY>
</HTML>Notice the form’s hidden variable named mode set to login, the CGI script’s main indicator.
<input type="hidden" name="mode" value="login"> CGI recognizes the mode login and runs the corresponding code.
The file intro.html and its stylesheet are useless without a destination. The ID field merely accepts input; CGI takes it and acts.
CGI functionality
The application’s CGI script is sp.py, listed later in the example sp.py. It serves four purposes: retrieve a customer profile from behind the switch using its ID; allow editing on the same page; accept updates and send the correct message back; and display all current offers in the OfferXMLStore. First it must import helpers, including the switch client (xsc) and the XMLMessage class, plus standard XML functionality:
import os
import cgi
from xsc import xsc
from XMLMessage import XMLMessage
from xml.dom.ext.reader.Sax2 import FromXmlFirst perform housekeeping: extract query-string data and determine which method to call.
# ''''''''''''''''''''''''''''''''''''''''''''
# HAUPTPROGRAMM
#
qs = cgi.parse_qs(os.environ["QUERY_STRING"])
mode = qs.get("mode", "")
id = qs.get("id", "")
print "Content-type: text/html"
print ""
print "<html>"
print """<HEAD><TITLE>Einkauf-Portal von Super-Billig GmbH (intro.html)</TITLE></HEAD><BODY>"""
print """<P align="center"><h1>Einkauf-Portal von Super-Billig GmbH</h1></P>"""
print """<p><h3>Klicken Sie <a href='/intro.html'>hier</a> zum Anmelden</h3>"""
print """ <h3>Klicken Sie <a href='/cgi-bin/sp.py?mode=getOffers'>hier</a> zum Sichten von Angeboten</h3></p>"""
if mode[0] == "updateProf":
doUpdateProfile()
if mode[0] == "login":
doLogin(id[0])
if mode[0] == "getOffers":
doGetOffers()
print "</body></html>"Three methods do most of the work: doUpdateProf, doLogin and doGetOffers. Examine these, where most XML processing occurs.
Retrieving profile information
The login button sends your ID and mode from the form in intro.html to the server. Detecting login mode calls the doLogin method. The login method takes an ID and builds the corresponding getProfile XML message:
def doLogin(id):
"""
doLogin(id) - diese Methode schnappt sich ein Kundenprofil
und zeigt es als XML im Browser an und stellt auch ein
Formular bereit, das dem Benutzer erlaubt, seine eigenen
Daten zu ändern.
"""
# Fahre den XML-Switch-Client hoch
xs = xsc()
xs.server = "centauri:2112"
# Bereite eine XML-Nachricht für den Server vor
xmlmsg = XMLMessage()
# Formatiere eine Nachricht für getProfile
xmlmsg.setXMLMessage("""
<message>
<header><rpc/></header>
<body>
<object class="CustomerProfile" method="getProfile">
<param>""" + id + """</param>
</object>
</body>
</message>
""")The code first instantiates the switch client and assigns centauri:2112 to the variable xsc.server. The switch thus runs on the machine centauri on port 2112. It then prepares the message containing the current user’s ID, letting the server return the right data.
Next send the getProfile request through the xsc class, instantiated as xs:
# Führe Aufruf im XML-Switch durch
xmlresp = xs.sendMessage(xmlmsg.getXMLMessage())
# Zeige die Antwort an
print "<P>Ihre empfangene Antwort:<br><xmp>"
print xmlresp
print "</xmp></p>"
# Setze Profil-XML-Nachricht auf und empfange DOM-Antwort
xmlmsg.setXMLMessage(xmlresp)
msgdom = xmlmsg.getXMLMessageDom()Once the doLogin method formats the message and sends it with xs.sendMessage, parse the result.
CustProfElement = msgdom.getElementsByTagName("CustomerProfile")[0]
CustProfElement.normalize()
# Picke ID-Nummer heraus
id = CustProfElement.getAttributeNS(None, "id")
print "<tr>"
print " <td colspan=2><b>Willkommen " + id + "</b></td>"
print "</tr>"
# Iteriere über die Kinder, erzeuge dabei vor-ausgefülltes Formular...
nodes = CustProfElement.childNodes
for node in nodes:
if node.nodeType == node.ELEMENT_NODE:
print "<tr><td>"
print "<b>" + node.nodeName + "</b>"
print "</td><td>"
for ec in node.childNodes:
print "<input type=text size=20 name='" + node.nodeName + "' "
print " value='" + ec.nodeValue + "'>"
print "</td></tr>"A new form now lets you update profile fields. The figure shows it prefilled in the browser.
Figure: The profile update form
Clicking Aktualisiere Profil triggers a different event in the server script sp.py. Your mode becomes updateProf and triggers another switch call. Your ID and mode wait in hidden form fields:
print "<input type='submit' value='Aktualisiere Profil'>"
print "<input type='hidden' name='id' value='" + id + "'>"
print "<input type='hidden' name='mode' value='updateProf'>"Hidden fields are not visible, but are still sent with GET or POST operations.
Updating profile information
Submitting the form invokes sp.py again, but now with mode updateProf. The mode selects a function, here doUpdateProfile.
To build the XML message, first extract form values from the query string:
xmlmsg = "<message><header><rpc/></header>\n"
xmlmsg += "<body><object class='CustomerProfile' method='updateProfile'>\n"
xmlmsg += "<param><CustomerProfile id="
xmlmsg += "'" + id[0] + "'>\n"
xmlmsg += "<firstname>" + qs.get("firstname","")[0].strip( ) + "</firstname>\n"
xmlmsg += "<lastname>" + qs.get("lastname","")[0].strip( ) + "</lastname>\n"
xmlmsg += "<address1>" + qs.get("address1","")[0].strip( ) + "</address1>\n"
xmlmsg += "<address2>" + qs.get("address2","")[0].strip( ) + "</address2>\n"
xmlmsg += "<city>" + qs.get("city","")[0].strip( ) + "</city>\n"
xmlmsg += "<state>" + qs.get("state","")[0].strip( ) +"</state>\n"
xmlmsg += "<zip>" + qs.get("zip","")[0].strip( ) +"</zip>\n"
xmlmsg += "</CustomerProfile></param></object></body></message>"
print xmlmsg
print "</xmp></p>"Each required field in an updateProfile XML request receives values from the submitted form. Then doUpdateProfile sends the new message to the switch:
xs = xsc()
xs.server = "centauri:2112"
resp = xs.sendMessage(xmlmsg)
print "<P>Empfangene Antwort:<br><xmp>"
print resp
print "</xmp></p>"
print "<h1>Erneut anmelden?</h1>"
print "<form name=login action='/cgi-bin/sp.py' method='GET'>"
print "Benutzen Sie Ihre aktuelle Kunden-ID:<br>"
print "<input type='text' size='15' name='id'"
print " value='" + id[0] + "'> "
print "<input type=submit value=' Anmelden '>"
print "<input type='hidden' name='mode' value='login'>"
print "</form>"Besides sending the request and confirming it, the script creates a new HTML form already containing your ID so you can log in again and inspect the changes.
Displaying all offers
Offer display is not the simplest XML, but should be manageable now. First prepare the XML message sent to the switch:
xs = xsc( )
xs.server = "centauri:2112"
xmlmsg = str("""<message>
<header><rpc/></header>
<body>
<object class="XMLOffer"
method="getAllOffers">
</object>
</body>
</message>""")
resp = xs.sendMessage(xmlmsg)The message is sent immediately. If successful, the method doGetOffers displays all valid offers:
offdom = FromXml(resp)
offers = offdom.getElementsByTagName("offer")
for offer in offers:
offer.normalize( )
for node in offer.childNodes:
if (node.nodeType == node.ELEMENT_NODE):
if (node.nodeName == "heading"):
print "<h3>" + node.firstChild.nodeValue + "</h3>"
if (node.nodeName == "description"):
print "<p>" + node.firstChild.nodeValue + "</p>"Familiar DOM operations traverse a node for its heading and description nodes, then extract the text below them.
The complete sp.py listing
The following example lists all of sp.py.
Example: sp.py
"""
sp.py - eine Folge von Webseiten und -formularen, die für den
Zugriff auf Daten Nachrichten an den XML-Switch schicken.
"""
import os
import cgi
from xsc import xsc
from XMLMessage import XMLMessage
from xml.dom.ext.reader.Sax2 import FromXml
def doLogin(id):
"""
doLogin(id) - diese Methode schnappt sich ein Kundenprofil und zeigt es als XML
im Browser an und stellt auch ein Formular bereit, das dem Benutzer erlaubt,
seine eigenen Daten zu ändern.
"""
# Fahre den XML-Switch-Client hoch
xs = xsc()
xs.server = "centauri:2112"
# Bereite eine XML-Nachricht für den Server vor
xmlmsg = XMLMessage()
# Formatiere eine Nachricht für getProfile
xmlmsg.setXMLMessage("""
<message>
<header><rpc/></header>
<body>
<object class="CustomerProfile" method="getProfile">
<param>""" + id + """</param>
</object>
</body>
</message>
""")
# Zeige an, wie der XML-Switch per CGI angesprochen wird
print "<p>In Ihrem Auftrag zu verschickende Nachricht:<br><xmp>"
print xmlmsg.getXMLMessage()
print "</xmp></p>"
# Führe Aufruf im XML-Switch durch
xmlresp = xs.sendMessage(xmlmsg.getXMLMessage())
# Zeige die Antwort an
print "<P>Ihre empfangene Antwort:<br><xmp>"
print xmlresp
print "</xmp></p>"
# Setze Profil-XML-Nachricht auf und empfange DOM-Antwort
xmlmsg.setXMLMessage(xmlresp)
msgdom = xmlmsg.getXMLMessageDom()
# Erzeuge ein Formular zum Editieren dieser neuen Profildaten
print "<h1>Editieren Sie Ihr Profil</h1>"
print "<form action='sp.py' method='GET'>"
print "<table width=450 border=1>"
# Parse Ergebnis
try:
CustProfElement = msgdom.getElementsByTagName("CustomerProfile")[0]
CustProfElement.normalize()
# Picke ID-Nummer heraus
id = CustProfElement.getAttributeNS(None, "id")
print "<tr>"
print " <td colspan=2><b>Willkommen " + id + "</b></td>"
print "</tr>"
# Iteriere über die Kinder, erzeuge dabei vor-ausgefülltes Formular...
nodes = CustProfElement.childNodes
for node in nodes:
if node.nodeType == node.ELEMENT_NODE:
print "<tr><td>"
print "<b>" + node.nodeName + "</b>"
print "</td><td>"
for ec in node.childNodes:
print "<input type=text size=20 name='" + node.nodeName + "' "
print " value='" + ec.nodeValue + "'>"
print "</td></tr>"
except:
print "<tr><td>Ausnahmezustand</td><td>Gefunden</td></tr>"
# Beende Formular
print "<tr><td colspan=2>"
print "<input type='submit' value='Aktualisiere Profil'>"
print "<input type='hidden' name='id' value='" + id + "'>"
print "<input type='hidden' name='mode' value='updateProf'>"
print "</td></tr>"
print "</table>"
print "</form>"
def doUpdateProfile():
"""
doUpdateProfile() - diese Methode wird aufgerufen, um ein Profil
mit einer updateProfile-XML-Nachricht zu aktualisieren.
"""
print "<p>Ihre aktualisierte Nachricht:<br><xmp>"
xmlmsg = "<message><header><rpc/></header>\n"
xmlmsg += "<body><object class='CustomerProfile' method='updateProfile'>\n"
xmlmsg += "<param><CustomerProfile id="
xmlmsg += "'" + id[0] + "'>\n"
xmlmsg += "<firstname>" + qs.get("firstname","")[0].strip() + "</firstname>\n"
xmlmsg += "<lastname>" + qs.get("lastname","")[0].strip() + "</lastname>\n"
xmlmsg += "<address1>" + qs.get("address1","")[0].strip() + "</address1>\n"
xmlmsg += "<address2>" + qs.get("address2","")[0].strip() + "</address2>\n"
xmlmsg += "<city>" + qs.get("city","")[0].strip() + "</city>\n"
xmlmsg += "<state>" + qs.get("state","")[0].strip() + "</state>\n"
xmlmsg += "<zip>" + qs.get("zip","")[0].strip() + "</zip>\n"
xmlmsg += "</CustomerProfile></param></object></body></message>"
print xmlmsg
print "</xmp></p>"
print "Aktualisierung wird vorgenommen..."
xs = xsc()
xs.server = "centauri:2112"
resp = xs.sendMessage(xmlmsg)
print "<P>Empfangene Antwort:<br><xmp>"
print resp
print "</xmp></p>"
print "<h1>Erneut anmelden?</h1>"
print "<form name=login action='/cgi-bin/sp.py' method='GET'>"
print "Benutzen Sie Ihre aktuelle Kunden-ID:<br>"
print "<input type='text' size='15' name='id'"
print " value='" + id[0] + "'> "
print "<input type=submit value=' Anmelden '>"
print "<input type='hidden' name='mode' value='login'>"
print "</form>"
def doGetOffers():
print "<p>Empfangen aller Angebote...</p>"
xs = xsc()
xs.server = "centauri:2112"
xmlmsg = str("""<message>
<header><rpc/></header>
<body>
<object class="XMLOffer" method="getAllOffers">
</object>
</body>
</message>""")
resp = xs.sendMessage(xmlmsg)
print "<p>Formatieren der Serverantwort..."
print "<h1>Angebote!</h1>"
offdom = FromXml(resp)
offers = offdom.getElementsByTagName("offer")
for offer in offers:
offer.normalize()
for node in offer.childNodes:
if (node.nodeType == node.ELEMENT_NODE):
if (node.nodeName == "heading"):
print "<h3>" + node.firstChild.nodeValue + "</h3>"
if (node.nodeName == "description"):
print "<p>" + node.firstChild.nodeValue + "</p>"
# ''''''''''''''''''''''''''''''''''''''''''''
# HAUPTPROGRAMM
#
qs = cgi.parse_qs(os.environ["QUERY_STRING"])
mode = qs.get("mode", "")
id = qs.get("id", "")
print "Content-type: text/html"
print ""
print "<html>"
print """<HEAD><TITLE>Einkauf-Portal von Super-Billig GmbH (intro.html)
</TITLE></HEAD><BODY>"""
print """<P align="center"><h1>Einkauf-Portal von Super-Billig GmbH</h1></P>"""
print """<p><h3>Klicken Sie <a href='/intro.html'>hier</a> zum Anmelden</h3>"""
print """ <h3>Klicken Sie <a href='/cgi-bin/sp.py?mode=getOffers'>hier</a>
zum Sichten von Angeboten</h3></p>"""
if mode[0] == "updateProf":
doUpdateProfile()
if mode[0] == "login":
doLogin(id[0])
if mode[0] == "getOffers":
doGetOffers()
print "</body></html>" Testing the site as a user
After meeting all website and XML integration prerequisites, test with a browser using these eight steps:
Ensure the web server runs and intro.html and sp.py work correctly.
Ensure the XML switch runs (runxs.py).
Ensure forms point to your web server and your
xsccalls point to the XML switch server.Open intro.html in your browser, enter a valid database ID, and click Anmelden.
View and edit the profile in the form below.
After editing, click the new form’s button Aktualisiere Profil to log in again.
Verify changes, then follow the link to offers.
Offers should appear as formatted HTML.
This application is the tip of the integration iceberg: browser to website, website to XML switch, then local objects retrieving relational database and flat-file information. Standard XML messages between distributed systems and intermediary routing bring much deeper integration and greater scalability.
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