16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

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 ensureDirec<strong>to</strong>ry, 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 direc<strong>to</strong>ries in Listing 22-4.<br />

Listing 22-3. The Web Site Construc<strong>to</strong>r (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 WebsiteConstruc<strong>to</strong>r(Dispatcher, ContentHandler):<br />

passthrough = False<br />

def __init__(self, direc<strong>to</strong>ry):<br />

self.direc<strong>to</strong>ry = [direc<strong>to</strong>ry]<br />

self.ensureDirec<strong>to</strong>ry()<br />

def ensureDirec<strong>to</strong>ry(self):<br />

path = os.path.join(*self.direc<strong>to</strong>ry)<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!