Changeset 1960
- Timestamp:
- 05/17/08 13:41:37
- Files:
-
- trunk/cherrypy/_cptools.py (modified) (1 diff)
- trunk/cherrypy/test/test_tools.py (modified) (3 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
trunk/cherrypy/_cptools.py
r1951 r1960 171 171 cherrypy.request.hooks.attach(self._point, self._wrapper, 172 172 priority=p, **conf) 173 174 175 class HandlerWrapperTool(Tool): 176 """Tool which wraps request.handler in a provided wrapper function. 177 178 The 'newhandler' arg must be a handler wrapper function that takes a 179 'next_handler' argument, plus *args and **kwargs. Like all page handler 180 functions, it must return an iterable for use as cherrypy.response.body. 181 182 For example, to allow your 'inner' page handlers to return dicts 183 which then get interpolated into a template: 184 185 def interpolator(next_handler, *args, **kwargs): 186 filename = cherrypy.request.config.get('template') 187 cherrypy.response.template = env.get_template(filename) 188 response_dict = next_handler(*args, **kwargs) 189 return cherrypy.response.template.render(**response_dict) 190 cherrypy.tools.jinja = HandlerWrapperTool(interpolator) 191 """ 192 193 def __init__(self, newhandler, point='before_handler', name=None, priority=50): 194 self.newhandler = newhandler 195 self._point = point 196 self._name = name 197 self._priority = priority 198 199 def callable(self): 200 innerfunc = cherrypy.request.handler 201 def wrap(*args, **kwargs): 202 return self.newhandler(innerfunc, *args, **kwargs) 203 cherrypy.request.handler = wrap 173 204 174 205 trunk/cherrypy/test/test_tools.py
r1824 r1960 91 91 cherrypy.tools.rotator = cherrypy.Tool('before_finalize', Rotator()) 92 92 93 def stream_handler(next_handler, *args, **kwargs): 94 cherrypy.response.output = o = StringIO.StringIO() 95 try: 96 response = next_handler(*args, **kwargs) 97 # Ignore the response and return our accumulated output instead. 98 return o.getvalue() 99 finally: 100 o.close() 101 cherrypy.tools.streamer = cherrypy._cptools.HandlerWrapperTool(stream_handler) 102 93 103 class Root: 94 104 def index(self): 95 105 return "Howdy earth!" 96 106 index.exposed = True 107 108 def tarfile(self): 109 cherrypy.response.output.write('I am ') 110 cherrypy.response.output.write('a tarfile') 111 tarfile.exposed = True 112 tarfile._cp_config = {'tools.streamer.on': True} 97 113 98 114 def euro(self): … … 207 223 'tools.gzip.priority': 10, 208 224 }, 225 # Handler wrappers 226 '/tarfile': {'tools.streamer.on': True} 209 227 } 210 228 app = cherrypy.tree.mount(root, config=conf) … … 333 351 method="POST", body=content) 334 352 self.assertBody(content) 353 354 def testHandlerWrapperTool(self): 355 self.getPage("/tarfile") 356 self.assertBody("I am a tarfile") 335 357 336 358

