XML technologies / XML / Python & XML / Python and distributed systems design / Creating the profile access class
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
The Profiles database is complemented by Python’s CustomerProfile class. Its objects handle XML database input and output, exposing methods for the XML switch. Basic profile operations retrieve, insert, update and delete profiles. Their arguments are XML profile data. XML packets let other applications produce and consume profiles without understanding or connecting directly to the database. A CustomerProfile could easily become the payload of a SOAP message. A profile packet looks like:
<CustomerProfile id="555-99JKK39">
<firstname>John</firstname>
<lastname>Doolittle</lastname>
<address1>396 Evergreen Terrace</address1>
<address2/>
<city>Springfield</city>
<state>WA</state>
<zip>98072</zip>
</CustomerProfile> Notice that the address2 element exists even when empty. Its DTD is:
<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT address1 (#PCDATA)>
<!ELEMENT address2 (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ELEMENT zip (#PCDATA)>
<!ATTLIST CustomerProfile id CDATA #REQUIRED>
<!ELEMENT CustomerProfile (firstname, lastname, address1, address2, city, state, zip)>A document using this DTD also needs a declaration:
<?xml version="1.0"?>
<!DOCTYPE CustomerProfile SYSTEM "CustomerProfile.dtd">
<CustomerProfile id="555-99JKK39">
<firstname>John</firstname>To keep this section focused, the Python class CustomerProfile does not enforce the DTD, although it accompanies the document and might be used later. When embedding CustomerProfile elements in an XML message, omit the prolog and include only CustomerProfile in the message.
Interfaces
The CustomerProfile class supports retrieval, insertion, updating and deletion. The XML switch uses it for runtime profile insertion and retrieval across the distributed system. All communication is XML, making backend storage flexible and avoiding direct database connections and table knowledge in distributed applications. They need only understand a CustomerProfile document.
getProfile(id)
Takes a customer profile ID and returns its data as a well-formed, valid CustomerProfile document string.
getProfileAsDom(id)
Like getProfile, but returns a DOM instance rather than XML text, ready for further DOM processing.
insertProfile(strXML)
Takes a valid, well-formed CustomerProfile XML document string and inserts it into the database.
updateProfile(strXML)
Like insertProfile, takes an XML CustomerProfile and updates the record matching its customer ID. Internally it deletes and inserts.
deleteProfile(id)
Takes a customer ID and deletes that database record.
Except for getProfile and getProfileAsDom, methods return either 1 or 0 (true or false), allowing these values in if statements.
Accessing profiles
The class CustomerProfile provides two retrieval methods: getProfile and getProfileAsDom. Both take a customerId argument. A simple test in runcp.py could use them as follows:
from CustomerProfile import CustomerProfile
from xml.dom.ext import PrettyPrint
cp = CustomerProfile( )
print "Ein XML-String:"
print cp.getProfile("234-E838839")
print "Oder ein DOM:"
dom = cp.getProfileAsDom("234-E838839")
PrettyPrint(dom) This assumes a database record with a customerId of 234-E838839. Running it prints two identical XML representations:
G:\pythonxml\c10> python runcp.py
Ein XML-String:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE CustomerProfile SYSTEM "CustomerProfile.dtd">
<CustomerProfile id='234-E838839'>
<firstname>John</firstname>
<lastname>Smith</lastname>
<address1>123 Evergreen Terrace</address1>
<address2>
</address2>
<city>Podunk</city>
<state>WA</state>
<zip>98072</zip>
</CustomerProfile>
Ein DOM:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE CustomerProfile SYSTEM "CustomerProfile.dtd">
<CustomerProfile id='234-E838839'>
<firstname>John</firstname>
<lastname>Smith</lastname>
<address1>123 Evergreen Terrace</address1>
<address2>
</address2>
<city>Podunk</city>
<state>WA</state>
<zip>98072</zip>
</CustomerProfile>Choose raw XML or DOM according to what you will do next. Return a string to another application or embed it in a SOAP packet, removing prolog declarations. For processing and possibly saving changes back to the database, DOM is probably better.
Connecting to the database
The code for getProfile is simple: check parameters, then prepare a connection with a simple SQL statement:
def getProfile(self, strId, dom=0):
"""
getProfile - gibt ein XML-Profil basierend auf der angegebenen ID
zurück. Liefert Null, falls nichts gefunden wird.
"""
if not strId:
return None
# Stelle Verbindung her
conn = odbc.odbc(CONNECTION_STRING)
cmd = conn.cursor()
cmd.execute("select * from customer where " +
"customerId = '" + strId + "'")
conn.close()Notice that strId is inspected first and the database command is a simple select *. Also note the third default parameter, dom=0. The switch is changed by getProfileAsDom so that getProfile returns DOM rather than a string.
Creating the XML document
Next retrieve the record and prepare XML with DOMImplementation.
# Hole Datensatz
prof_fields = cmd.fetchone()
if prof_fields is None:
return None
# Erzeuge XML aus den Datenfeldern,
# erzeuge CustomerProfile-doctype
doctype = implementation.createDocumentType(
"CustomerProfile", "", "CustomerProfile.dtd")
# Erzeuge neues Dokument mit doctype
newdoc = implementation.createDocument(
"", "CustomerProfile", doctype)
rootelem = newdoc.documentElement
# Erzeuge ein id-Attribut im Wurzelelement
rootelem.setAttribute("id", prof_fields[CUSTOMER_ID])The code uses the DOMImplementation class to create XML. First the method fetchone fetches one row into prof_fields. Indices in prof_fields are named constants defined in the module CustomerProfile, listed later in the example CustomerProfile.py. Then create a document-type object referring to the previously created file CustomerProfile.dtd and pass it to implementation.createDocument to create an empty XML document element.
This shows how easily DOMImplementation builds XML compared with manual strings, discussed later. Arrange elements in a simple loop:
# Erzeuge Dictionary mit Feldwerten
fields = ["firstname", prof_fields[FIRSTNAME],
"lastname", prof_fields[LASTNAME],
"address1", prof_fields[ADDRESS1],
"address2", prof_fields[ADDRESS2],
"city", prof_fields[CITY],
"state", prof_fields[STATE],
"zip", prof_fields[ZIP],
]
# Laufe durch Dictionary, füge Elemente und Elementtext hinzu
for pos in range(0, len(fields), 2):
# Erzeuge das Element
thisElement = newdoc.createElement(fields[pos])
# Teste auf leere Werte und konvertiere in weiche Nullen
if fields[pos + 1] is None:
fields[pos + 1] = ""
# Füge Feldwert als Kindtextknoten an Element hinzu
thisElement.appendChild(newdoc.createTextNode(fields[pos+1]))
rootelem.appendChild(thisElement)Put database values in a list, iterating to create and append elements. Use a list, not a dictionary, because DTD compliance requires element order. Python dictionaries return keys in arbitrary order and do not preserve insertion order.
Using a list is easy: Python’s range advances two entries at a time, using the current one as element name and the next as character data.
With XML ready, choose a string or DOM according to the call. Remember, getProfile is called by getProfileAsDom with extra parameters:
# Liefere DOM oder String, je nachdem, wie wir aufgerufen wurden...
if dom:
return newdoc.documentElement
else:
# Gib String zurück
strXML = StringIO.StringIO()
PrettyPrint(newdoc.documentElement, strXML)
return strXML.getvalue()The call is now complete. For a string result, use StringIO with the PrettyPrint method to write XML as though the string were a file. Building with DOMImplementation has several advantages over manual strings. DTD and encoding declarations no longer require complicated string assignments, and programmatic changes are easier to maintain. DOM also makes structural changes more flexible: moving and editing nodes is easier than parsing and editing text. Sometimes you still concatenate XML fragments and create another DOM, returning to a programmatically accessible representation.
Returning DOM instead of text
The method getProfileAsDom works like getProfile but returns DOM rather than XML text.
def getProfileAsDom(self, strId):
"""
Diese Methode ruft getProfile mit einer gesetzten dom-Option auf,
was bewirkt, daß getProfile sein erzeugtes DOM-Objekt zurückgibt
statt eines XML-Strings.
"""
return self.getProfile(strId, 1)Intuitive helpers are often easier than overloading a method with conditional parameters users must learn.
Inserting and deleting profiles
The method insertProfile is the other workhorse of the CustomerProfile class. Whereas getProfile builds a DOM, insertProfile dismantles one to store its values. Deletion is simpler: one SQL statement with the customer ID goes directly to the database.
The method insertProfile adds new CustomerProfile XML documents to the database. Clients need neither database connections nor table knowledge. Distributed applications can more readily share XML structure than database structure, which may require support for proprietary data types.
Use insertProfile with XML text such as:
cp = CustomerProfile( )
cp.insertProfile("<String mit XML>")Returns true on success and false on failure. Exceptions may also propagate from the code.
Inserting a profile
The code for insertProfile is simple but involves more DOM work. Like getProfile, it checks input and creates DOM, (instead of a DOM-Implementation in getProfile):
def insertProfile(self, strXML):
"""
insertProfile nimmt einen XML-String-Happen, parst
dessen Felder und fügt ihn in die Profil-Datenbank
ein. Eine Ausnahme wird ausgelöst, falls XML nicht
wohlgeformt ist oder die Kunden-ID fehlt oder falls der
SQL-Aufruf schiefgeht. Liefert 1 bei Erfolg, sonst 0.
"""
if not strXML:
raise Exception("Kein XML-String angegeben.")
# Beginne Parsen von XML
try:
doc = FromXml(strXML)
except:
print "Fehler beim Parsen des Dokuments."
return 0
# Normalisiere Leerraum und hole Wurzelelement
doc.normalize()
elem = doc.documentElementMost important are calls to FromXml and to the document’s normalize method. The FromXml method belongs to the Sax2 reader package and builds DOM from raw XML text.
The doc.normalize call also matters. The CustomerProfile XML fragment is simple, with short character data requiring no surrounding whitespace. Carriage returns introduced by forms or GUIs can safely be removed. This is crucial to how insertProfile handles elements: without normalization, text could span several nodes and firstChild would return only the first. Calling normalize merges adjacent text nodes.
Next extract values from the new DOM for an SQL statement.
# Extrahiere Werte aus XML-Paket
customerId = elem.getAttributeNS(None, 'id')
firstname = self.extractNodeValue(elem, "firstname")
lastname = self.extractNodeValue(elem, "lastname")
address1 = self.extractNodeValue(elem, "address1")
address2 = self.extractNodeValue(elem, "address2")
city = self.extractNodeValue(elem, "city")
state = self.extractNodeValue(elem, "state")
zip = self.extractNodeValue(elem, "zip")
# Bereite SQL-Anweisung vor
strSQL = ("insert into Customer values ("
"'" + firstname + "', "
"'" + lastname + "', "
"'" + address1 + "', "
"'" + address2 + "', "
"'" + city + "', "
"'" + state + "', "
"'" + zip + "', "
"'" + customerId + "')")Extract the customerId attribute from the root and call the helper extractNodeValue for each required element. It extracts a descendant’s text; an internal helper avoids duplication across methods. Use the results of extractNodeValue to build an SQL insert statement. The implementation of extractNodeValue is:
def extractNodeValue(self, elem, elemName):
"""
Interne Methode zum Parsen von UNIQUE-Elementen
für Textwerte oder zum Ersetzen von leeren Strings.
"""
e = elem.getElementsByTagName(elemName)[0].firstChild
if e is None:
return ""
else:
return e.nodeValueIt finds a child element, checks its character data and returns an empty string if missing.
Submit the prepared SQL to the database:
# Stelle Verbindung her
conn = odbc.odbc(CONNECTION_STRING)
cmd = conn.cursor()
# Führe SQL-Anweisung aus
if (not cmd.execute(strSQL)):
raise Exception("SQL-Anweisung fehlgeschlagen.")
conn.close()
return 1Successful communication returns a positive 1 to the caller.
Deleting a profile
Deletion simply uses the customer ID as parameter in an SQL delete statement:
def deleteProfile(self, strId):
"""
deleteProfile erwartet eine Kundenprofil-ID und löscht den entsprechenden
Satz in der Datenbank. Liefert 1 bei Erfolg, sonst 0.
"""
if not strId:
return 0
# Stelle Datenbankverbindung her
conn = odbc.odbc(CONNECTION_STRING)
cmd = conn.cursor()
ok = cmd.execute("delete from customer where customerId = '"
+ strId + "'")):
conn.close()
return ok and 1 or 0SQL success is reported as 1 or 0.
Updating profiles
Updating through the CustomerProfile class is simple. Pass updateProfile new XML whose customerId matches an existing ID. The old record is deleted and replaced.
Internally, the method updateProfile uses insertProfile and deleteProfile, but exists to make CustomerProfile easier to use.
To extract the customerId from XML, quickly instantiate DOM to parse it:
def updateProfile(self, strXML):
"""
Diese Hilfsfunktion erwartet ein neues Kundenprofil als
XML-Paket. Sie extrahiert die Kunden-ID und ruft dann
deleteProfile und insertProfile mit Hilfe des neuen XML auf.
Der Rückgabewert für das Einfügen wird an den Aufrufer
weitergegeben, außer das Löschen schlägt fehl, wobei er dann
zurückgegeben wird, aber das Einfügen nicht stattfindet.
"""
# Parse Dokument nach Kunden-ID
try:
doc = FromXml(strXML)
customerId = doc.documentElement.getAttributeNS('','id')
except:
print "Fehler beim Parsen des Dokuments."
return 0As shown, FromXml again turns XML text into DOM. Extract the customerId by calling getAttributeNS. Using reader.Sax2 requires a namespace-aware DOM method rather than getAttribute. This hotly debated implementation bug will hopefully be fixed after publication, allowing getAttribute too. Join the XML-SIG for the lively discussion. With this customerId, reuse existing insert and delete methods:
# Versuche zu löschen und füge basierend auf customerId ein
if self.deleteProfile(customerId):
return self.insertProfile(strXML)
else:
return 1Their return values go directly to the caller.
The complete CustomerProfile class
The CustomerProfile class does substantial work, storing customer information as XML across the network. Applications accessing the CustomerProfile class use this without knowing the database or storage medium. XML can also be forwarded to an application hosting CustomerProfile for updates. Ideally, the caller need not even know CustomerProfile, only construct and send a suitable SOAP or XML message. After building the switch we do this later in The XML switch client and CGI functionality.
The complete listing of CustomerProfile follows.
Example: CustomerProfile.py
"""
CustomerProfile.py
"""
import dbi
import odbc
import StringIO
from xml.dom import implementation
from xml.dom.ext import PrettyPrint
from xml.dom.ext.reader.Sax2 import FromXml
# Definiere einige globale Variablen für die Klasse
CONNECTION_STRING = "Profiles/webuser/w3bus3r"
FIRSTNAME = 0
LASTNAME = 1
ADDRESS1 = 2
ADDRESS2 = 3
CITY = 4
STATE = 5
ZIP = 6
CUSTOMER_ID = 7
class CustomerProfile:
"""
CustomerProfile - verwaltet das Speichern und Laden von
XML-Kundenprofilen in/von einer relationalen Datenbank.
"""
def getProfileAsDom(self, strId):
"""
Diese Methode ruft getProfile mit einer gesetzten dom-Option auf,
was bewirkt, daß getProfile sein erzeugtes DOM-Objekt zurückgibt
statt eines XML-Strings.
"""
return self.getProfile(strId, 1)
def getProfile(self, strId, dom=0):
"""
getProfile - gibt ein XML-Profil basierend auf der angegebenen ID
zurück. Liefert Null, falls nichts gefunden wird.
"""
if not strId:
return None
# Stelle Verbindung her
conn = odbc.odbc(CONNECTION_STRING)
cmd = conn.cursor()
cmd.execute("select * from customer where " +
"customerId = '" + strId + "'")
conn.close()
# Hole Datensatz
prof_fields = cmd.fetchone()
if prof_fields is None:
return None
# Erzeuge XML aus den Datenfeldern,
# erzeuge CustomerProfile-doctype
doctype = implementation.createDocumentType(
"CustomerProfile", "", "CustomerProfile.dtd")
# Erzeuge neues Dokument mit doctype
newdoc = implementation.createDocument(
"", "CustomerProfile", doctype)
rootelem = newdoc.documentElement
# Erzeuge ein id-Attribut im Wurzelelement
rootelem.setAttribute("id", prof_fields[CUSTOMER_ID])
# Erzeuge Dictionary mit Feldwerten
fields = ["firstname", prof_fields[FIRSTNAME],
"lastname", prof_fields[LASTNAME],
"address1", prof_fields[ADDRESS1],
"address2", prof_fields[ADDRESS2],
"city", prof_fields[CITY],
"state", prof_fields[STATE],
"zip", prof_fields[ZIP],
]
# Laufe durch Dictionary, füge Elemente und Elementtext hinzu
for pos in range(0, len(fields), 2):
# Erzeuge das Element
thisElement = newdoc.createElement(fields[pos])
# Teste auf leere Werte und konvertiere in weiche Nullen
if fields[pos + 1] is None:
fields[pos + 1] = ""
# Füge Feldwert als Kindtextknoten zu Element hinzu
thisElement.appendChild(newdoc.createTextNode(fields[pos+1]))
rootelem.appendChild(thisElement)
# Liefere DOM oder String, je nachdem, wie wir aufgerufen wurden...
if dom:
return newdoc.documentElement
else:
# Gib String zurück
strXML = StringIO.StringIO()
PrettyPrint(newdoc.documentElement, strXML)
return strXML.getvalue()
def insertProfile(self, strXML):
"""
insertProfile nimmt einen XML-String-Happen, parst
dessen Felder und fügt ihn in die Profil-Datenbank
ein. Eine Ausnahme wird ausgelöst, falls XML nicht
wohlgeformt ist oder die Kunden-ID fehlt oder falls der
SQL-Aufruf schiefgeht. Liefert 1 bei Erfolg, sonst 0.
"""
if not strXML:
raise Exception("Kein XML-String angegeben.")
# Beginne Parsen von XML
try:
doc = FromXml(strXML)
except:
print "Fehler beim Parsen des Dokuments."
return 0
# Normalisiere Leerraum und hole Wurzelelement
doc.normalize()
elem = doc.documentElement
# Extrahiere Werte aus XML-Paket
customerId = elem.getAttributeNS(None, 'id')
firstname = self.extractNodeValue(elem, "firstname")
lastname = self.extractNodeValue(elem, "lastname")
address1 = self.extractNodeValue(elem, "address1")
address2 = self.extractNodeValue(elem, "address2")
city = self.extractNodeValue(elem, "city")
state = self.extractNodeValue(elem, "state")
zip = self.extractNodeValue(elem, "zip")
# Bereite SQL-Anweisung vor
strSQL = ("insert into Customer values ("
"'" + firstname + "', "
"'" + lastname + "', "
"'" + address1 + "', "
"'" + address2 + "', "
"'" + city + "', "
"'" + state + "', "
"'" + zip + "', "
"'" + customerId + "')")
# Stelle Verbindung her
conn = odbc.odbc(CONNECTION_STRING)
cmd = conn.cursor()
# Führe SQL-Anweisung aus
if (not cmd.execute(strSQL)):
raise Exception("SQL-Anweisung fehlgeschlagen.")
conn.close()
return 1
def extractNodeValue(self, elem, elemName):
"""
Interne Methode zum Parsen von UNIQUE-Elementen
für Textwerte oder zum Ersetzen von leeren Strings.
"""
e = elem.getElementsByTagName(elemName)[0].firstChild
if e is None:
return ""
else:
return e.nodeValue
def updateProfile(self, strXML):
"""
Diese Hilfsfunktion erwartet ein neues Kundenprofil als
XML-Paket. Sie extrahiert die Kunden-ID und ruft dann
deleteProfile und insertProfile mit Hilfe des neuen XML auf.
Der Rückgabewert für das Einfügen wird an den Aufrufer
weitergegeben, außer das Löschen schlägt fehl, wobei er dann
zurückgegeben wird, aber das Einfügen nicht stattfindet.
"""
# Parse Dokument nach Kunden-ID
try:
doc = FromXml(strXML)
customerId = doc.documentElement.getAttributeNS('','id')
except:
print "Fehler beim Parsen des Dokuments."
return 0
# Versuche zu löschen und füge basierend auf customerId ein
if self.deleteProfile(customerId):
return self.insertProfile(strXML)
else:
return 1
def deleteProfile(self, strId):
"""
deleteProfile erwartet eine Kundenprofil-ID und löscht den entsprechenden
Satz in der Datenbank. Liefert 1 bei Erfolg, sonst 0.
"""
if not strId:
return 0
# Stelle Datenbankverbindung her
conn = odbc.odbc(CONNECTION_STRING)
cmd = conn.cursor()
ok = cmd.execute("delete from customer where customerId = '" + strId + "'"):
conn.close()
return ok and 1 or 0Notice in CustomerProfile.py the constants defined at the beginning as database field markers. They make individual fields in record lists much easier to use.
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