Serving multiple WSGI applications in one server
Using the internal CherryPy HTTP server
The builtin HTTP server delivered with CherryPy follows the WSGI interface and is therefore usable to host non-CherryPy applications as the following example demonstrates:
from cherrypy import wsgiserver def forum(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) return ['Hello world from a forum!\n'] def blog(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) return ['Hello world from a blog!\n'] # Here we set our application to the script_name '/' wsgi_apps = [('/blog', blog), ('/forum', forum)] server = wsgiserver.CherryPyWSGIServer(('localhost', 8080), wsgi_apps, server_name='localhost') if __name__ == '__main__': try: server.start() except KeyboardInterrupt: server.stop()
Using a third-party server
Imagine you gave the following CherryPy application:
import cherrypy class Blog: @cherrypy.expose def index(self): return "You're reading a blog!" cpwsgiapp = cherrypy.Application(Root(), '/apps/blog')
As you can notice we wrap our CherryPy application into a cherrypy.Application that respects the WSGI interface and therefore can be used in a WSGI context. We also explicitely specify the prefix at which we will be mounting our application.
And the following WSGI application:
def trivial_app(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) return ['Hello world!\n']
They can be served from one single server instance:
# http://www.owlfish.com/software/wsgiutils/ from wsgiutils import wsgiServer # http://pythonpaste.org/ from paste.urlmap import URLMap def map_apps_to_prefix(): map_apps = URLMap({}) map_apps['/'] = trivial_app map_apps['/apps/blog'] = cpwsgiapp return map_apps if __name__ == '__main__': cherrypy.engine.start(blocking=False) server = wsgiServer.WSGIServer(('localhost', 8080), {'':map_apps_to_prefix(),}) server.serve_forever()
In this example we do not use the built-in HTTP server provided by CherryPy but an external one coming with the wsgiutils package. We also use the paste package to perform the URL mapping to our applications.
Note the call to cherrypy.engine.start(blocking=False). The blocking parameter must be set to False in order to initialize the CherryPy machinery and yet give back the control to the calling process so that the wsgiutils package can start a server and block itself.

