comparison lxmlmiddleware/middleware.py @ 2:bb7d50d54cb6

correct huge mistake in how i try to get the response
author k0s <k0scist@gmail.com>
date Sun, 24 Jan 2010 23:13:03 -0500
parents 2bf25337048f
children ca1f58f5bad4
comparison
equal deleted inserted replaced
1:2bf25337048f 2:bb7d50d54cb6
2 LXML middleware 2 LXML middleware
3 """ 3 """
4 4
5 import lxml.html 5 import lxml.html
6 from lxml import etree 6 from lxml import etree
7 from webob import Request, Response
7 8
8 class LXMLMiddleware(object): 9 class LXMLMiddleware(object):
9 """ 10 """
10 abstract base class; inherit from and implement the manipulate method 11 abstract base class; inherit from and implement the manipulate method
11 """ 12 """
18 19
19 # set up to recompose on the way out 20 # set up to recompose on the way out
20 if not 'lxml.recomposer' in environ: 21 if not 'lxml.recomposer' in environ:
21 environ['lxml.recomposer'] = self 22 environ['lxml.recomposer'] = self
22 23
24 request = Request(environ)
23 # get the response 25 # get the response
24 response = self.app(environ, start_response) 26 response = request.get_response(self.app)
27 response.decode_content()
25 28
26 # get the DOM, if not already made 29 # get the DOM, if not already made
27 if not isinstance(response, etree._Element): 30 # TODO: check response.content_type
31 if not 'lxml.etree' in environ:
28 try: 32 try:
29 response = etree.fromstring(''.join(response)) 33 environ['lxml.etree'] = etree.fromstring(response.body)
30 except etree.XMLSyntaxError: # not XML 34 except etree.XMLSyntaxError: # not XML
31 environ.pop('lxml.recomposer') 35 environ.pop('lxml.recomposer')
32 return response 36 return response(environ, start_response)
33 37
34 # manipulate the DOM 38 # manipulate the DOM
35 response = self.manipulate(environ, response) 39 environ['lxml.etree'] = self.manipulate(environ, environ['lxml.etree'])
36 40
37 # recompose the DOM if the last in the chain 41 # recompose the DOM if the last in the chain
38 if environ['lxml.recomposer'] is self: 42 if environ['lxml.recomposer'] is self:
39 response = [ lxml.html.tostring(response) ] 43 response.body = lxml.html.tostring(environ['lxml.etree'])
40 44
41 # return the response 45 # return the response
42 return response 46 return response(environ, start_response)
47
43 48
44 def manipulate(self, environ, tree): 49 def manipulate(self, environ, tree):
45 """manipulate the DOM; should return an etree._Element""" 50 """manipulate the DOM; should return an etree._Element"""
46 return tree 51 return tree
47 52