在同一个 repo 中,有 vhost recipe。但是它使用共享应用程序。我看不到让cherrypy.dispatch.VirtualHost 使用单独安装的应用程序的方法。这是因为cherrypy.serving.request.app 是在调用调度程序之前设置的。假设您有以下内容。
hostmap = {
'api.domain.com' : '/app1',
'www.domain.com' : '/app2'
}
cherrypy.tree.mount(App1(), '/app1', appConfig1)
cherrypy.tree.mount(App2(), '/app2', appConfig2)
cherrypy.dispatch.VirtualHost 所做的只是将域前缀添加到当前 url,例如请求http://www.domain.com/foo 将导致/app2/foo/ 作为内部路径发送到下一个调度程序,通常是cherrypy.dispatch.Dispatcher。然而,后者将尝试使用当前设置为空应用程序的cherrypy.serving.request.app 查找页面处理程序,因为 CherryPy 树中没有任何内容与/foo 路径相对应。所以它什么也找不到。
您只需要替换前缀即可更改当前应用程序。也就是把that line改成这个。
cherrypy.serving.request.app = cherrypy.tree.apps[prefix]
但是因为cherrypy.dispatch.VirtualHost 很小,你可以很容易地重写你的代码。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cherrypy
from cherrypy._cpdispatch import Dispatcher
config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 80,
'server.thread_pool' : 8
},
'hostmap' : {
'api.domain.com' : '/app1',
'www.domain.com' : '/app2'
}
}
appConfig1 = {
'/' : {
'tools.json_out.on' : True
}
}
appConfig2 = {
'/' : {
'tools.encode.encoding' : 'utf-8'
}
}
def VirtualHost(nextDispatcher = Dispatcher(), useXForwardedHost = True, **domains):
def dispatch(pathInfo):
request = cherrypy.serving.request
domain = request.headers.get('Host', '')
if useXForwardedHost:
domain = request.headers.get('X-Forwarded-Host', domain)
prefix = domains.get(domain, '')
if prefix:
request.app = cherrypy.tree.apps[prefix]
result = nextDispatcher(pathInfo)
# Touch up staticdir config. See
# https://bitbucket.org/cherrypy/cherrypy/issue/614.
section = request.config.get('tools.staticdir.section')
if section:
section = section[len(prefix):]
request.config['tools.staticdir.section'] = section
return result
return dispatch
class App1:
@cherrypy.expose
def index(self):
return {'bar': 42}
class App2:
@cherrypy.expose
def index(self):
return '<em>foo</em>'
if __name__ == '__main__':
config['/'] = {'request.dispatch': VirtualHost(**config['hostmap'])}
cherrypy.tree.mount(App1(), '/app1', appConfig1)
cherrypy.tree.mount(App2(), '/app2', appConfig2)
cherrypy.quickstart(config = config)