fumanchuが述べたように、への複数の呼び出しを使用して、サイトにさまざまなサブセクションを作成できますcherrypy.tree.mount
。以下は、フロントエンドWebアプリと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()
のインスタンスを作成すると、WebService
2つの異なるWebアプリケーションが初期化されます。1つ目は、私のフロントエンドアプリケーションです。これは、に存在しweb.Application
、で提供され/
ます。2つ目は私の安らかなAPIで、に住んでいてweb.API
、で提供され/api
ます。
2つのビューの構成も異なります。たとえば、APIがメソッドディスパッチを使用し、APIへのアクセスがHTTP基本認証によって管理されるように指定しました。
のインスタンスを作成したらWebService
、必要に応じてそのインスタンスでstartまたはstopを呼び出すことができ、すべてのクリーンアップが処理されます。
かなりクールなもの。