A rather special kind of Tool is the HandlerTool. HandlerTools? provide a way to hook-up code (functions, or callables in general) that will run just before a normal request-handler is called. On the outset, a handler-tool is little more a Tool that has been created with its point being before_handler. That is:
cherrypy.tools.my_tool = cherrypy.Tool('before_handler', my_func)
cherrypy.tools.my_handler_tool = cherrypy._cptools.HandlerTool(my_func)
are, on the outset, very similar. There are, though, two significant differences:
- The handler tool provides an additional method (called handler)
that can be used to create a normal request-handler from it, like this:
class MyClass: my_handler = cherrypy.tools.my_handler_tool.handler()
With this my_handler has become a regular request-handler, already exposed and all.
- If the handler tool is used as a hook, it provides a way to
suppress the normal request-handler from running. This is very useful in several cases (e.g. you can use handler-tools to authorize access to parts of your application. If authorization fails you can suppress the normal request handler from running). To do this the tool's callable must return True. If instead it returns False then the normal handler will run as soon as the tool returns. You can think of it like this, if you prefer: The return value of the HandlerTool's callable indicates whether the tool has handled the request or not. If not the normal handler will be called to do so.