在具有多个类的CherryPy Python Web应用程序中配置主机和端口

时间:2013-04-11 09:55:10

标签: python cherrypy

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

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

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

1 个答案:

答案 0 :(得分:1)

我想我想出了如何解决它。我添加了这一行:

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

之后的

行之后

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

我认为我的类获得数据库配置的原因是我通过 setConfig()调用手动传递它。这仅传递应用程序配置,而不是全局配置。 mount()调用显然不会将配置数据传播到它安装的对象,正如我认为的那样。

此外, update()调用必须在 mount()调用之后,或者引发异常。

我不确定这是否是组织此代码的最佳方式。这暂时有效,但总是欢迎更好的想法。