As fumanchu mentioned, you can create different subsections to your site with multiple calls to cherrypy.tree.mount
. Below is a simplified version of a site that I'm working on that consists of both a front-end web app and a restful API:
import cherrypy
import web
class WebService(object):
def __init__(self):
app_config = {
'/static': {
# enable serving up static resource files
'tools.staticdir.root': '/static',
'tools.staticdir.on': True,
'tools.staticdir.dir': "static",
},
}
api_config = {
'/': {
# the api uses restful method dispatching
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
# all api calls require that the client passes HTTP basic authentication
'tools.authorize.on': True,
}
}
cherrypy.tree.mount(web.Application(), '/', config=app_config)
cherrypy.tree.mount(web.API(), '/api', config=api_config)
# a blocking call that starts the web application listening for requests
def start(self, port=8080):
cherrypy.config.update({'server.socket_host': '0.0.0.0', })
cherrypy.config.update({'server.socket_port': port, })
cherrypy.engine.start()
cherrypy.engine.block()
# stops the web application
def stop(self):
cherrypy.engine.stop()
Creating an instance of WebService
initializes two different web applications. The first is my front-end application, which lives at web.Application
and will be served up at /
. The second is my restful API, which lives at web.API
and will be served up at /api
.
The two views have different configurations too. For instance, I've specified that the api uses method dispatching, and that access to it is governed by HTTP Basic authentication.
Once you create an instance of WebService
, you can call start or stop on it as necessary, and it takes care of all of the cleanup.
Pretty cool stuff.