Search code examples
pythonflaskwebserverwsgicherrypy

How to get CherryPy to listen only on a specific host


I have a flask app that I want to deploy using CherryPy's built in server. I chose CherryPy so that the app can be deployed without having to reverse proxy (ie. nginx in front).

I'm having trouble getting CherryPy to listen for requests on just a single hostname.

Say I'm serving 2 sites: test1.com and test2.com (and have them set in my hosts file to point back to localhost). My /etc/hosts file:

127.0.0.1    test1.com test2.com

CherryPy is serving test1.com, test2.com doesn't have anything serving it.

My cherrypy file is as follows:

import cherrypy

from my_test_flask_app import app

if __name__ == '__main__':

    cherrypy.tree.graft(app, "/")

    cherrypy.server.unsubscribe()

    server = cherrypy._cpserver.Server()

    server.socket_host = "test1.com"
    server.socket_port = 8030
    server.thread_pool = 30

    server.subscribe()

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

Set up this way, I go to test1.com:8030 on my browser and it works as expected.

But when I go to test2.com:8030, the same app is served. I expected it not to serve anything, since CherryPy isn't set up to listen for test2.com.

To me, it seems that CherryPy is just listening for everything on the given port (8030), and treating the socket_host part as if its 0.0.0.0

Am I missing something here? I've looked through lots of docs and tutorials, but all things suggest that this code snippet should be working as I expected.

Thanks


Solution

  • Here's how you can setup what you want...

    root = Root()
    RootApp = cherrypy.Application(root)
    Domain2App = cherrypy.Application(root)
    SecureApp = cherrypy.Application(Secure())
    
    vhost = cherrypy._cpwsgi.VirtualHost(RootApp,
        domains={'www.domain2.example': Domain2App,
                 'www.domain2.example:443': SecureApp,
                 })
    
    cherrypy.tree.graft(vhost)
    

    https://cherrypy.readthedocs.org/en/3.3.0/refman/_cpwsgi.html#classes

    Hope this helps!