Dif
Dif

Reputation: 23

Declaration of CherryPy Tool fails

I'm trying to declare a new tool to the CherryPy toolbox following the examples from the docs: Docs CherryPy Tools.

According to the examples I have written:

import cherrypy

def myTool():
    print ("myTool")

class Root(object):
    @cherrypy.expose
    @cherrypy.tools.mytool()
    def index(self):
        return "Hello World!"

if __name__ == '__main__':
    cherrypy.tools.mytool = cherrypy.Tool('before_finalize', myTool)
    cherrypy.quickstart(Root(), '/')

This results in the following error:

Traceback (most recent call last):
  File "server.py", line 6, in <module>
    class Root(object):
  File "server.py", line 8, in Root
    @cherrypy.tools.mytool()
  AttributeError: 'Toolbox' object has no attribute 'mytool'

However if I change the notation to the following it works as expected.

import cherrypy

def myTool():
    print ("myTool")

class Root(object):
    @cherrypy.expose
    def index(self):
        return "Hello World!"
    index._cp_config = {'tools.mytool.on': True}

if __name__ == '__main__':
    cherrypy.tools.mytool = cherrypy.Tool('before_finalize', myTool)
    cherrypy.quickstart(Root(), '/')

The docs says that both methods have the same effect, but not in my case. If anyone knows what I'm doing wrong I'll be very grateful.

The tool should not be defined globally, hence the @cherrypy.tools.mytool() notation.

I'm using python 3.6.

Upvotes: 0

Views: 719

Answers (1)

cyraxjoe
cyraxjoe

Reputation: 5741

The problem is the misunderstanding of the evaluation order of python (top-down), at the time the class is defined the tool has not been defined.

You can define the tool in another file import at the top (before the class definition) and it should work.

The second form works, because the configuration is done indirectly using strings in the config, not the real tool objects.

Upvotes: 1

Related Questions