cherrypy两个服务器不同的端口

时间:2014-01-06 09:48:35

标签: python cherrypy

我想在不同的端口和不同的应用程序上运行2个cherry py服务器。

我设法同时运行它们,但我如何连接应用程序和服务器? 我希望能够去

http://127.0.0.1:3141/
得到server1

http://127.0.0.1:3145/
得到server2

多个服务器的cherrypy docs示例不足以让我理解如何做到这一点 这是Multiple servers/ports

我的代码

import cherrypy

class App1(object):
    @cherrypy.expose
    def index(self):
         return ('server1')

class App2(object):
    @cherrypy.expose
    def index(self):
         return ('server2')


cherrypy.server.unsubscribe()

server1 = cherrypy._cpserver.Server()
server1.socket_port=3141
server1._socket_host="127.0.0.1"
server1.thread_pool=2
server1.subscribe()

server2 = cherrypy._cpserver.Server()
server2.socket_port=3145
server2._socket_host="127.0.0.1"
server2.thread_pool=2
server2.subscribe()

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

3 个答案:

答案 0 :(得分:2)

如果您的应用需要(或可以)从不同的路径(例如http://127.0.0.1:3141/app1http://127.0.0.1:3145/app2)提供服务,请为每个应用使用tree.mount()。如果必须从根路径提供这两个应用,请查看VirtualHost以获取想法。

答案 1 :(得分:0)

我认为你需要两个不同的目录。在每个目录/应用程序中,您为应用程序放置了一个配置文件。 例如,我有这样的事情:

[global]
server.socket_host = "ip_address"
server.socket_port = 8080
server.thread_pool = 10


[/]
tools.staticdir.root = "/path/to/your/app"
tools.encode.on = True
tools.decode.on = True

看看here

答案 2 :(得分:0)

调整了一段时间后,我无法将每个应用程序都安装到特定端口。 行为是每个端口都响应每个应用程序,因此我添加了一个工具来过滤每个应用程序上的端口,如下例所示:

import cherrypy
from cherrypy._cpserver import Server


@cherrypy.tools.register('before_handler')
def port_filter():
    if cherrypy.request.app.root.request_port != cherrypy.request.local.port:
        raise cherrypy.NotFound()


class App1(object):
    def __init__(self, request_port):
        self.request_port = request_port

    @cherrypy.expose
    @cherrypy.tools.port_filter()
    def index(self):
        return "Hello world from app1"


class App2(object):
    def __init__(self, request_port):
        self.request_port = request_port

    @cherrypy.expose
    @cherrypy.tools.port_filter()
    def index(self):
        return "Hello world from app2"


class MyServer(Server):
    def __init__(self, host, port, thread_pool=10):
        Server.__init__(self)
        self.socket_port = port
        self._socket_host = host
        self.thread_pool = thread_pool
        self.subscribe()


if __name__ == '__main__':
    # Unsubscribe default server
    cherrypy.server.unsubscribe()

    # Setup server for each port
    MyServer(host='0.0.0.0', port=80)
    MyServer(host='0.0.0.0', port=8080)

    # Mount applications to specific port
    cherrypy.tree.mount(App1(80), "/app1")
    cherrypy.tree.mount(App2(8080), "/app2")

    # Start!
    cherrypy.engine.start()
    cherrypy.engine.block()
相关问题