Search code examples
pythoncherrypy

Configuring host and port in a CherryPy Python web app with more than one class


I have a simple Cherrypy web application, including two classes. The init code looks like this:

c = MyClass()
c.updates = AnotherClass()
app = cherrypy.tree.mount(c, '/', 'myapp.config')
c.setConfig(app.config)
c.updates.setConfig(app.config)
cherrypy.engine.start()
cherrypy.engine.block()

The setConfig method for both classes is just a line of code to store some database configuration:

def setConfig(self, conf):
    self.config = conf['Database']

The configuration file myapp.config looks like this:

[global]
server.socket_host = "0.0.0.0"
server.socket_port = 80

[/]
tools.staticdir.root = com.stuff.myapp.rootDir + '/html'

[Database]
dbtable: "mydbtable"
username: "user"
password: "pass"

When I start the lot, the application gets the database config data, and correctly serves static files from the /html directory, but it only listens on localhost on 8080. I get this on the console:

[11/Apr/2013:10:03:58] ENGINE Bus STARTING
[11/Apr/2013:10:03:58] ENGINE Started monitor thread 'Autoreloader'.
[11/Apr/2013:10:03:58] ENGINE Started monitor thread '_TimeoutMonitor'.
[11/Apr/2013:10:03:58] ENGINE Serving on 127.0.0.1:8080
[11/Apr/2013:10:03:58] ENGINE Bus STARTED

I definitely must have done something wrong. It's as if the global part of the configuration doesn't get applied. How can I fix it?


Solution

  • I think I figured out how to solve it. I added this line:

    cherrypy.config.update('myapp.config')
    

    after the line that says

    app = cherrypy.tree.mount(c, '/', 'myapp.config')
    

    I think the reason why my classes were getting the Database configuration is that I pass it manually with the setConfig() calls. This passes the application configuration only, not the global configuration. The mount() call apparently doesn't propagate the configuration data to the objects it mounts, as I thought it would do.

    Furthermore, the update() call must be after the mount() call, or an exception is raised.

    I'm not sure whether this is the best way to organize this code. This works for now, but better ideas are always welcome.