1

我有一个简单的 Cherrypy Web 应用程序,包括两个类。初始化代码如下所示:

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()

这两个类的 setConfig 方法只是一行代码来存储一些数据库配置:

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

配置文件 myapp.config 如下所示:

[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"

当我开始很多时,应用程序获取数据库配置数据,并正确地从 /html 目录提供静态文件,但它只在 8080 上侦听 localhost。我在控制台上得到了这个:

[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

我肯定做错了什么。就好像配置的全局部分没有得到应用。我该如何解决?

4

1 回答 1

1

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.

于 2013-04-12T10:28:26.137 回答