0
|
1 """
|
|
2 LXML middleware
|
|
3 """
|
|
4
|
|
5 from lxml import etree
|
|
6
|
|
7 class LXMLMiddleware(object):
|
|
8 """
|
|
9 abstract base class; inherit from and implement the manipulate method
|
|
10 """
|
|
11
|
|
12 def __init__(self, app):
|
|
13 self.app = app
|
|
14
|
|
15 ### methods dealing with HTTP
|
|
16 def __call__(self, environ, start_response):
|
|
17
|
|
18 # set up to recompose on the way out
|
|
19 if not 'lxml.recomposer' in environ:
|
|
20 environ['lxml.recomposer'] = self
|
|
21
|
|
22 # get the response
|
|
23 response = self.app(environ, start_response)
|
|
24
|
|
25 # get the DOM, if not already made
|
|
26 if not isinstance(response, etree._Element):
|
|
27 response = etree.fromstring(''.join(response))
|
|
28
|
|
29 # manipulate the DOM
|
|
30 response = self.manipulate(environ, response)
|
|
31
|
|
32 # recompose the DOM if the last in the chain
|
|
33 if environ['lxml.recomposer'] is self:
|
|
34 response = [ etree.tostring(response) ]
|
|
35
|
|
36 # return the response
|
|
37 return response
|
|
38
|
|
39 def manipulate(self, environ, tree):
|
|
40 """manipulate the DOM; should return an etree._Element"""
|
|
41 return tree
|
|
42
|