简体   繁体   English

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

[英]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. 我有一个简单的Cherrypy Web应用程序,包括两个类。 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: 这两个类的setConfig方法仅是一行代码,用于存储一些数据库配置:

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

The configuration file myapp.config looks like this: 配置文件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"

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: 当我开始大量工作时,该应用程序获取数据库配置数据,并从/ 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

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? 我该如何解决?

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. 我认为我的班级获得数据库配置的原因是我通过setConfig()调用手动传递了它。 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. mount()调用显然不会像我认为的那样将配置数据传播到它所安装的对象。

Furthermore, the update() call must be after the mount() call, or an exception is raised. 此外, update()调用必须在mount()调用之后,否则会引发异常。

I'm not sure whether this is the best way to organize this code. 我不确定这是否是组织此代码的最佳方法。 This works for now, but better ideas are always welcome. 目前,此方法有效,但始终欢迎更好的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM