python - cherrypy 无法使用多个服务器和多个端口按预期工作

标签 python cherrypy

我想使用 cherrypy 在两个单独的端口上提供两个单独的类。一类是私有(private)的,希望它仅在被防火墙阻止的端口上提供服务,并希望使用需要凭据的服务器。另一个我想公开。

这是我的代码:

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 上为私有(private)类提供服务!

我正在使用 cherrypy 3.1.2

我正在尝试遵循这些示例:1 2 3 彼此差异很大、不完整或似乎有错误。

最佳答案

您的代码的问题是您为这两个实例调用了 cherrypy.tree.mount()。但这会将它们安装在同一个 CherryPy 实例中,TestPrivate 有效地覆盖了 TestPublic。这也是只有私服可见的原因。

即使挂载多个根对象是可能的(据我所知,目前还不可能),您的代码中没有任何地方可以显式地将 server1 分配给 TestPublic server2TestPrivate。您只需调用 subscribe() 并希望 CherryPy 解决它 - 这是行不通的。

正如 Anders Waldenborg 所指出的,查看 VirtualHost 调度程序:

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

但为此,您必须将两个根对象合并为一个。

否则,按照 Celada 的建议,只需启动两个单独的 CherryPy 进程即可。

关于python - cherrypy 无法使用多个服务器和多个端口按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7999431/

相关文章:

python - 在 CherryPy 中检查每个页面加载时的登录状态

时间序列的Python聚合

Python 访问 SQL Server 2008

python - 单元格中的 Pandas 字符串到新行

python - Cherrypy base64 图像编码未按预期工作

python - 具有多个 url 路径的 CherryPy MethodDispatcher

Python - 装饰器 - 试图访问方法的父类

python - 如何对Python嵌套列表中的数据进行分类

python - Cherrypy 和内容类型

python - 在mako模板: call python function within html string中