XML technologies / XML / Python & XML / Python and distributed systems design / Creating an XML data store
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
The third component of this chapter’s distributed application is an “XML offer data store.” It stores the special offers retailers often make to customers. In this imaginary application, various offers are available over the network. Different distributed applications can access them for different reasons.
A web application might retrieve offers dynamically to present according to customers’ purchases or spending habits, applying a stylesheet before displaying them on a web page. An intranet application could likewise access offers to modify or update them.
This section builds that XML offer store. The next section writes another Python class similar to CustomerProfile to provide fairly transparent network access to it.
One large XML file
The offer store is one large XML document on disk. The access component mentioned above, developed later, traverses this file and returns the right offers to its caller. An offer’s basic structure, with empty elements, is:
<offer>
<id/>
<internal-name/>
<heading/>
<description/>
<discount/>
<discount-type/>
<expires/>
<disclaimer/>
</offer>The next example presents a first complete store containing only two offers. Feel free to add your own.
Example: OfferXMLStore.xml
<?xml version="1.0" encoding="iso-8859-1"?>
<OfferXMLStore>
<offer>
<id>9908d093j4p3j33</id>
<internal-name>RabattMehrAls1000</internal-name>
<heading>20% auf alle Bestellungen über EUR 1000,00</heading>
<description>Als Anreiz für Sie, noch mehr zu kaufen, bieten wir 20% Mengenrabatt auf alle Ihre Bestellungen über EUR 1000,-! Wir bieten Ihnen diesen riesigen Rabatt, weil Sie so ein wichtiger Kunde für uns sind. So sehr lieben wir Sie!</description>
<discount>20</discount>
<discount-type>prozent</discount-type>
<expires>2002-11-21</expires>
<disclaimer>Dieser Rabatt unterliegt bestimmten Einschränkungen. Die Ware darf nicht in irgendeiner anderen Weise bereits reduziert sein. Der Rabatt kann in einigen Fällen nicht gewährt werden, wenn wir denken, dass Sie das Produkt auch ohne Rabatt kaufen würden. Wir können den Rabatt jederzeit wieder zurücknehmen, leider auch nach Ihrer Bestellung.</disclaimer>
</offer>
<offer>
<id>222833fgjQZ3j30</id>
<internal-name>Ramsch</internal-name>
<heading>20% auf alle Ramsch-Produkte</heading>
<description>Zur Reduzierung unserer anscheinend unverkäuflichen Ware gewähren wir einen 20%-Abschlag auf alle als Ramsch ausgezeichneten Produkte! Wir bieten Ihnen diesen Rabatt, weil Sie so ein wichtiger Kunde für uns sind. So sehr lieben wir Sie!</description>
<discount>20</discount>
<discount-type>prozent</discount-type>
<expires>2002-11-21</expires>
<disclaimer>Dieser Rabatt unterliegt bestimmten Einschränkungen. Die Ware muss als Ramsch ausgezeichnet sein. In einigen Fällen können als Ramsch markierte Produkte dieses Etikett im Moment des Kaufens verlieren. Falls Ihnen das passieren sollte, wird leider der vollständige Kaufpreis fällig.</disclaimer>
</offer>
</OfferXMLStore>These two offers are enough to start. OfferXMLStore is simply a large XML file on disk. As it grows, parsing and manipulation overhead increases. Beyond a certain point, it is better to put OfferXMLStore in a database. Although XML representation is essential, a real database is a much more efficient physical store than a large text file. XML excels as a document format and “glue language.” You do not want one XML document containing a gigabyte of information, but a gigabyte of XML documents in your database. The flexible access object built next lets you change the underlying storage without affecting XML entering and leaving the component.
Creating an XML access object
Here we create a component accessing the XML store. Such objects conveniently encapsulate a data source from its users. The earlier CustomerProfile object already hid an ODBC source behind an XML facade. The XMLOffer class provides methods to store, find and modify offers.
The interfaces
The interfaces of the class XMLOffer closely resemble those of CustomerProfile, with the addition of the method getAllOffers. They let network applications interact with the store entirely through XML, without knowing or caring about its storage mechanism. Keeping the same interface but changing the implementation, you could make the XMLOffer class use a database instead of an XML file. The change would be completely transparent to clients.
getOffer(id)
Takes an ID string and returns the corresponding offer as plain XML in a string.
getOfferAsDomElement(id)
As expected, this works like the corresponding method in CustomerProfile and returns a DOM-Element object rather than a string.
getAllOffers( )
Returns the entire OfferXMLStore as a string.
insertOffer(strXML)
Takes XML as an argument and inserts it into the store.
updateOffer(strXML)
Like CustomerProfile.updateProfile, takes an offer as XML, deletes the matching stored offer and inserts the new one.
deleteOffer(id)
Takes an ID and removes the corresponding offer from the XML store.
These interfaces make working with XML offers as easy as possible for network applications.
This class and CustomerProfile will be placed in the XML switch. They could easily sit behind a web or CORBA server, but for simplicity they are importable classes available to the XML switch.
Using the XMLOffer class
Using the XMLOffer class is easy. Provided you have the file OfferXMLStore.xml on disk, as shown in the example OfferXMLStore.xml, you can start using the XMLOffer class like this:
from XMLOffer import XMLOffer
xo = XMLOffer( )
print xo.getOffer('9908d093j4p3j33')The result is an offer with a matching ID child element. Conversely, if a website sends an offer or a GUI passes a text field’s XML as a string, use the method insertOffer:
xo.insertOffer(strXMLOffer) All these interfaces really are very simple.
Building the XMLOffer class
The XMLOffer class is simple, but its implementation relies heavily on DOM and XPath. Like CustomerProfile, the XMLOffer class normally returns a 1 or 0 after each method call, except of course for methods returning XML.
To understand how the XMLOffer class wraps the large OfferXMLStore in helper functions such as get, insert, update or delete, you must understand various ways of manipulating XML. The implementation of the class XMLOffer illustrates DOM and XPath usage.
Search methods
To retrieve an offer, the class accepts an ID string and uses XPath to locate the matching offer in the store:
offerdoc = FromXmlStream("OfferXMLStore.xml")
offer = Evaluate("offer[id='" + strId + "']",
offerdoc.documentElement)XPath searches for the supplied ID (strId) in offer elements in the store. A match is returned as an offer element. If you requested an element node (offer), call getOfferAs DomElement; for a string, call getOffer:
if dom:
return offer[0]
else:
strXML = StringIO.StringIO( )
PrettyPrint(offer[0], strXML)
return strXML.getvalue( )Of course, getOfferAsDomElement works just like getProfile in the class CustomerProfile. It simply calls its shorter-named counterpart with an optional parameter requesting a node instead of a string.
The method getAllOffers returns the store directly by reading the entire file as a string.
# Öffne Angebotsdatei
fd = open("OfferXMLStore.xml", "r")
doc = fd.read( )
fd.close( )
# Gib großen String zurück
return docEditing methods
Several methods edit and manage stored offers. The method insertOffer adds new offers. The methods updateOffer and deleteOffer provide further management.
The method insertOffer creates a DOM instance from incoming XML to check its well-formedness and potentially its validity if desired. It is converted to a string and substituted for the closing tag of the OfferXMLStore. This quickly and simply adds the element to the document. String manipulation is possible because the incoming XML was first a DOM instance, where it could be validated.
The method updateOffer extracts the ID and performs deletion followed by insertion. The method deleteOffer extracts an ID and removes the node from a DOM instance:
try:
targetNode = Evaluate("offer[id=\"" + strId + "\"]",
xmlstore.documentElement)
except:
print "XPath-Auswertung fehlerhaft."
return 0
# Benutze Node.removeChild(XPathResult)
try:
xmlstore.documentElement.removeChild(targetNode[0])
except:
# Entweder es existierte nicht, oder
# der XPath-Aufruf hat nichts ergeben...
return 0XPath locates the specific ID, and the call Evaluate returns the actual node. It is then passed to the method removeChild() of the node documentElement. The remaining code writes the file back to disk. The next example shows XMLOffer.py.
Example: XMLOffer.py
"""
XMLOffer.py
"""
import StringIO
from xml.dom.ext.reader.Sax2 import FromXmlStream
from xml.dom.ext.reader.Sax2 import FromXml
from xml.dom.ext import PrettyPrint
from xml.xpath import Evaluate
class XMLOffer:
def getOffer(self, strId, dom=0):
"""
getOffer nimmt eine ID als Parameter und liefert das entsprechende Angebot aus dem
XML-Datenlager als XML-String oder als DOM, falls der dritte Parameter gesetzt wurde.
"""
# Erzeuge Dokument aus dem Datenlager
offerdoc = FromXmlStream("OfferXMLStore.xml")
# Benutze XPath, um mit Hilfe von Kind-ID-Zeichendaten
# auf ein spezielles Angebotselement zu verweisen
offer = Evaluate("offer[id='" + strId + "']",
offerdoc.documentElement)
# Entscheide, welche Version zurückgegeben wird, DOM oder String
if dom:
# Liefere Angebotselement
return offer[0]
else:
# Konvertiere in String
strXML = StringIO.StringIO()
PrettyPrint(offer[0], strXML)
return strXML.getvalue()
def getOfferAsDomElement(self, strId):
"""
getOfferAsDomElement funktioniert genauso wie getOffer,
liefert jedoch eine DOM-Elementinstanz, statt eines
Strings. Diese Methode ruft einfach getOffer mit einem
auf 1 gesetzten dom-Schalter auf (der dritte Parameter).
"""
return self.getOffer(strId, 1)
def getAllOffers(self):
"""
getAllOffers liefert das gesamte Datenlager
als String.
"""
# Öffne Angebotsdatei
fd = open("OfferXMLStore.xml", "r")
doc = fd.read()
fd.close()
# Gib großen String zurück
return doc
def insertOffer(self, strOfferXML):
"""
insertOffer nimmt einen XML-String und fügt
ihn zum XML-Datenlager hinzu.
"""
if not strOfferXML:
return None
# Erzeuge DOM aus Eingabedaten
newoffer = FromXml(strOfferXML)
#----
# optional: hier könnten Sie mit Ihrem neuen DOM-Objekt und offer.dtd validieren;
# siehe Kap. 7 für Details darüber, wie man xmlproc zur Validierung benutzt...
#----
# Schütte DOM in einen String aus
newXmlOffer = StringIO.StringIO()
PrettyPrint(newoffer.documentElement, newXmlOffer)
# Hole Inhalt in einen Puffer
rd = open("OfferXMLStore.xml", "r")
bf = rd.readlines()
rd.close()
# Suche und ersetze in Puffer
wd = open("OfferXMLStore.xml", "w")
for lp in range(len(bf)):
if (bf[lp].rfind("</OfferXMLStore>") > -1):
# Ersetze End-Tag des Wurzelelements mit frischem
# Angebot und Wurzelelement-End-Tag
bf[lp] = bf[lp].replace("</OfferXMLStore>",
newXmlOffer.getvalue() + "</OfferXMLStore>")
# Schreibe neuen Puffer auf Platte
wd.writelines(bf)
wd.close()
return 1
def deleteOffer(self, strId):
"""
deleteOffer nimmt einen ID-String und löscht diesen
Angebotsknoten aus dem Dokument OfferXMLStore.xml
"""
# Lies Datenlager in ein DOM und schliesse es dann
try:
xmlstore = FromXmlStream("OfferXMLStore.xml")
except:
print "XML-Datenlager konnte nicht geöffnet werden."
return 0
# Benutze XPath, um den id-Knoten zurückzugeben
# offer/[id='<id>']
try:
targetNode = Evaluate("offer[id=\"" + strId + "\"]",
xmlstore.documentElement)
except:
print "XPath-Auswertung fehlerhaft."
return 0
# Benutze Node.removeChild(XPathResult)
try:
xmlstore.documentElement.removeChild(targetNode[0])
except:
# Entweder es existierte nicht, oder der XPath-Aufruf hat nichts ergeben...
return 0
# Öffne Lager erneut, zum Schreiben,
# mache ein PrettyPrint des DOMs,
# schließe Lager wieder
fd = open("OfferXMLStore.xml", "w")
PrettyPrint(xmlstore, fd)
fd.close()
return 1
def updateOffer(self, strOfferXML):
if not strOfferXML:
return 0
else:
try:
offerId = Evaluate("id/text()",
FromXml(strOfferXML).documentElement)
if (not self.deleteOffer(offerId[0].nodeValue)
or not self.insertOffer(strOfferXML)):
print "Konnte nicht löschen oder einfügen."
return 0
except:
print "Konnte Angebot nicht aktualisieren."
return 0
return 1The class XMLOffer is easy to use. The next distributed-system component is the XML switch, routing individual messages between applications.
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