我这里有一个Python程序。 它使用CherryPy来创建服务器。
# coding:utf-8
import os.path
import cherrypy
from app import application
def main():
try:
currentDir_s = os.path.dirname(os.path.abspath(__file__))
except:
currentDir_s = os.path.dirname(os.path.abspath(sys.executable))
cherrypy.Application.currentDir_s = currentDir_s
configFileName_s = 'server.conf'
if os.path.exists(configFileName_s) == False:
configFileName_s = None
cherrypy.engine.autoreload.unsubscribe()
cherrypy.engine.timeout_monitor.unsubscribe()
cherrypy.quickstart(application.Application_cl(), config=configFileName_s)
if __name__ == '__main__':
main()
在“server.conf”中配置服务器:
[global]
tools.log_headers.on: True
tools.sessions.on: False
tools.encode.on: True
tools.encode.encoding:"utf-8"
server.socket_port: 8080
server.socket_timeout:60
server.thread_pool: 10
server.environment: "production"
log.screen: True
[/]
tools.staticdir.root: cherrypy.Application.currentDir_s
tools.staticdir.on = True
tools.staticdir.dir = '.'
有一件事,我不明白,这一行(python代码中的第13行):
cherrypy.Application.currentDir_s = currentDir_s
我在互联网上搜索了这个,但我找不到任何东西。 “cherrypy.Application”有什么作用?为什么我必须做这个任务(cherrypy.Application.currentDir_s = currentDir_s)?
答案 0 :(得分:2)
我搜索了cherrypy源代码,这是我发现的。
在_cptree.py
模块中,您将找到Application
类。在此之下,有一个Tree
类,其中mount
方法用于绑定应用程序(例如cherrypy.tree.mount(Root(), "/", config=config)
)
def mount(self, root, script_name="", config=None):
...
当您查看此方法时,您将看到以下代码;
def mount(self, root, script_name="", config=None):
...
if isinstance(root, Application):
app = root
if script_name != "" and script_name != app.script_name:
raise ValueError(
"Cannot specify a different script name and pass an "
"Application instance to cherrypy.mount")
script_name = app.script_name
else:
app = Application(root, script_name)
# If mounted at "", add favicon.ico
if (script_name == "" and root is not None
and not hasattr(root, "favicon_ico")):
favicon = os.path.join(os.getcwd(), os.path.dirname(__file__),
"favicon.ico")
root.favicon_ico = tools.staticfile.handler(favicon)
if config:
app.merge(config)
self.apps[script_name] = app
因此,代码说您传递给mount
方法的每个对象(应用程序)都是Application
实例或包含在Application
实例中。那为什么会这样呢?当您检查Application
课程Tree
上课时,您会看到如下所示的__call__
课程;
def __call__(self, environ, start_response):
return self.wsgiapp(environ, start_response)
是的,你现在看到它,它是wsgi
界面。
因此,Application
是一个用于樱桃应用程序的wsgi包装器。
当您查看cherrypy的源代码时,您可能会学到很多东西。我希望这个答案可以帮助你。