使用多个服务器和多个端口时,cherrypy不能按预期工作

1 投票
1 回答
1614 浏览
提问于 2025-04-17 05:35

我想用cherrypy在两个不同的端口上提供两个不同的类。其中一个类是私有的,我希望它只在一个被防火墙阻挡的端口上提供,并且需要使用凭证的服务器。另一个类我希望是公开的。

这是我的代码:

import cherrypy
from cherrypy import _cpserver
from cherrypy import _cpwsgi_server

class TestPublic:
    @cherrypy.expose
    def index(self):
        return 'welcome!'

class TestPrivate:
    @cherrypy.expose
    def index(self):
        return 'secret!'        

if __name__ == '__main__':   
    users = {'admin':'password'}
    config1 = {'/':{
        'server.thread_pool' : 50,
        'server.environment' : 'production',
        }}
    config2 = {'/admin':{
        'server.thread_pool' : 50,
        'tools.digest_auth.on': True,
        'tools.digest_auth.realm': 'Some site',
        'tools.digest_auth.users': users,
        }}    

    cherrypy.server.unsubscribe()
    cherrypy.tree.mount(TestPublic(), script_name ='/', config=config1)
    cherrypy.tree.mount(TestPrivate(), script_name ='/admin', config=config2)        
    server1 = _cpserver.Server()
    server2 = _cpserver.Server()
    server1.bind_addr = ('0.0.0.0', 8080)
    server2.bind_addr = ('0.0.0.0', 8888)
    adapter1 = _cpserver.ServerAdapter(cherrypy.engine, server1)
    adapter2 = _cpserver.ServerAdapter(cherrypy.engine, server2)
    adapter1.subscribe()
    adapter2.subscribe()

    cherrypy.engine.start()
    cherrypy.engine.block()

结果是,8888端口上什么都没有提供,而私有类却在8080端口上提供了!

我使用的是cherrypy 3.1.2版本。

我试图参考这些例子: 1 2 3,但它们之间差别很大,有些不完整,或者看起来有错误。

1 个回答

4

你代码的问题在于,你对两个实例都调用了 cherrypy.tree.mount()。这样做会把这两个实例都放在同一个 CherryPy 实例里,结果是 TestPrivate 会覆盖掉 TestPublic。这也是为什么你只能看到私有服务器的原因。

即使可以挂载多个根对象(我目前了解到的情况是不能),你的代码中也没有明确把 server1 指定给 TestPublic,把 server2 指定给 TestPrivate。你只是调用了 subscribe(),希望 CherryPy 能自己搞定,但这样是行不通的。

正如 Anders Waldenborg 提到的,看看虚拟主机调度器:

http://docs.cherrypy.org/stable/refman/_cpdispatch.html#cherrypy._cpdispatch.VirtualHost

不过你得把这两个根对象合并成一个。

否则,就像 Celada 建议的那样,启动两个独立的 CherryPy 进程。

撰写回答