Mercurial > hg > lxmlmiddleware
diff lxmlmiddleware/middleware.py @ 0:d1067d921e97
initial import of lxml middleware
author | k0s <k0scist@gmail.com> |
---|---|
date | Sun, 24 Jan 2010 12:00:39 -0500 |
parents | |
children | 2bf25337048f |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lxmlmiddleware/middleware.py Sun Jan 24 12:00:39 2010 -0500 @@ -0,0 +1,42 @@ +""" +LXML middleware +""" + +from lxml import etree + +class LXMLMiddleware(object): + """ + abstract base class; inherit from and implement the manipulate method + """ + + def __init__(self, app): + self.app = app + + ### methods dealing with HTTP + def __call__(self, environ, start_response): + + # set up to recompose on the way out + if not 'lxml.recomposer' in environ: + environ['lxml.recomposer'] = self + + # get the response + response = self.app(environ, start_response) + + # get the DOM, if not already made + if not isinstance(response, etree._Element): + response = etree.fromstring(''.join(response)) + + # manipulate the DOM + response = self.manipulate(environ, response) + + # recompose the DOM if the last in the chain + if environ['lxml.recomposer'] is self: + response = [ etree.tostring(response) ] + + # return the response + return response + + def manipulate(self, environ, tree): + """manipulate the DOM; should return an etree._Element""" + return tree +