04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

434 CHAPTER 22 ■ PROJECT 3: XML FOR ALL OCCASIONS<br />

def endPage(self):<br />

self.passthrough = False<br />

self.writeFooter()<br />

self.out.close()<br />

The first line of startPage may look a little intimidating, but it is more or less the same as<br />

the first line of ensureDirectory, except that you add the file name (and give it an .html suffix).<br />

The full source code of the program is shown in Listing 22-3. You can find a list of the<br />

generated files and directories in Listing 22-4.<br />

Listing 22-3. The Web Site Constructor (website.py)<br />

from xml.sax.handler import ContentHandler<br />

from xml.sax import parse<br />

import os<br />

class Dispatcher:<br />

def dispatch(self, prefix, name, attrs=None):<br />

mname = prefix + name.capitalize()<br />

dname = 'default' + prefix.capitalize()<br />

method = getattr(self, mname, None)<br />

if callable(method): args = ()<br />

else:<br />

method = getattr(self, dname, None)<br />

args = name,<br />

if prefix == 'start': args += attrs,<br />

if callable(method): method(*args)<br />

def startElement(self, name, attrs):<br />

self.dispatch('start', name, attrs)<br />

def endElement(self, name):<br />

self.dispatch('end', name)<br />

class WebsiteConstructor(Dispatcher, ContentHandler):<br />

passthrough = False<br />

def __init__(self, directory):<br />

self.directory = [directory]<br />

self.ensureDirectory()<br />

def ensureDirectory(self):<br />

path = os.path.join(*self.directory)<br />

if not os.path.isdir(path): os.makedirs(path)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!