Search code examples
cherrypy

CherryPy Tool: How to register custom tool correctly?


I want to create a simple tool but fail to register it correctly. As soon as I add it to any method I get the error:

AttributeError: 'Toolbox' object has no attribute 'authenticate'

I tried

cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)

and

@cherrypy.tools.register('before_handler')
def authenticate():

The issue I likely have is placing the function in the wrong place. I have a main file launching the server and all apps:

#config stuff

if __name__ == '__main__':
    cherrypy.engine.unsubscribe('graceful', cherrypy.log.reopen_files)
    logging.config.dictConfig(LOG_CONF)
    cherrypy.tree.mount(app1(), '/app1')
    cherrypy.tree.mount(app2(), '/app2')
    cherrypy.quickstart(app3)

This file is launched by a systemd unit.

If I put the authenticate function in the config area, it doesn't work. If i put it in one of the apps directly and only use it in that app, it doesn't work. Always the same error.

So where do I have to place it to make this work?


Solution

  • Another case of me falling into the python definition order matters trap.

    Doesn't work:

    class MyApp(object): 
    
        #....
    
    @cherrypy.tools.register('on_start_resource')
    def authenticate():
        #....
    

    Works:

    @cherrypy.tools.register('on_start_resource')
    def authenticate():
        #....
    
    class MyApp(object):