![](/img/trans.png)
[英]Configuring host and port in a CherryPy Python web app with more than one class
[英]Running more than one class in Cherrypy
我正在尝试使用索引等构建一个小网站,并在/ api中创建一个我想要的api。
例如:
class Site(object):
@cherrypy.expose
def index(self):
return "Hello, World!"
@cherrypy.expose
def contact(self):
return "Email us at..."
@cherrypy.expose
def about(self):
return "We are..."
class Api(object):
@cherrypy.expose
def getSomething(self, something):
db.get(something)
@cherrypy.expose
def putSomething(self, something)
所以,我希望能够访问mysite.com/contact和mysite.com/Api/putSomething
如果我使用cherrypy.quickstart(Site())
,我只会获取Site下的页面。
我认为有一种方法可以将类Api映射到/ Api下,但我找不到它。
更新(2017年3月13日):下面的原始答案已经过时,但我要离开它,因为它是为了反映所提出的原始问题。
原答案:
查看默认调度程序。 Dispatching的完整文档。
引用文档:
root = HelloWorld()
root.onepage = OnePage()
root.otherpage = OtherPage()
在上面的示例中,URL
http://localhost/onepage
将指向第一个对象,URLhttp://localhost/otherpage
将指向第二个对象。 像往常一样,这种搜索是自动完成的。
import cherrypy
class Root:
def index(self):
return "Hello, world!"
index.exposed = True
class Admin:
def user(self, name=""):
return "You asked for user '%s'" % name
user.exposed = True
class Search:
def index(self):
return search_page()
index.exposed = True
cherrypy.root = Root()
cherrypy.root.admin = Admin()
cherrypy.root.admin.search = Search()
正如fumanchu所提到的,您可以通过多次调用cherrypy.tree.mount
为您的站点创建不同的子部分。 下面是我正在处理的网站的简化版本,其中包括一个前端Web应用程序和一个安静的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
实例初始化两个不同的Web应用程序。 第一个是我的前端应用程序,它位于web.Application
,将在/
。 第二个是我的restful API,它位于web.API
,将在/api
。
这两个视图也有不同的配置。 例如,我已经指定api使用方法调度,并且对它的访问由HTTP基本身份验证控制。
创建WebService
实例后,可以根据需要调用start或stop,并负责所有清理工作。
很酷的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.