Running cherrypy on multiple ports (example)


As a continuation of my previous post on how to run cherrypy as an SSL server as HTTPS (port 443), this tutorial show how to run a single cherrypy instance on multiple ports for both HTTP (port 80) and HTTPS (port 443)

We need to do a few things differently than in most examples out there like how to set configs when not using the quickstart() function and creating multiple Server() objects. But after reading through the source code a little it becomes clear.

import cherrypy

class RootServer:
    @cherrypy.expose
    def index(self, **keywords):
        return "it works!"

if __name__ == '__main__':
    site_config = {
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': "/home/ubuntu/my_website/static"
        },
        '/support': {
            'tools.staticfile.on': True,
            'tools.staticfile.filename': "/home/ubuntu/my_website/templates/support.html"
        }
    }
    cherrypy.tree.mount(RootServer())

    cherrypy.server.unsubscribe()

    server1 = cherrypy._cpserver.Server()
    server1.socket_port=443
    server1._socket_host='0.0.0.0'
    server1.thread_pool=30
    server1.ssl_module = 'pyopenssl'
    server1.ssl_certificate = '/home/ubuntu/my_cert.crt'
    server1.ssl_private_key = '/home/ubuntu/my_cert.key'
    server1.ssl_certificate_chain = '/home/ubuntu/gd_bundle.crt'
    server1.subscribe()

    server2 = cherrypy._cpserver.Server()
    server2.socket_port=80
    server2._socket_host="0.0.0.0"
    server2.thread_pool=30
    server2.subscribe()

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

6 responses to “Running cherrypy on multiple ports (example)”

Leave a Reply