我需要配置支持以下URL方案的RESTful样式URL:
我想使用MethodDispatcher,以便上面的每一个都可以有GET / POST / PUT / DELETE函数。我让它为第一个和第二个工作,但无法弄清楚如何配置子部分的调度程序。我有这本书,但它几乎没有涵盖这一点,我在网上找不到任何样本。
以下是我当前配置MethodDispatcher的方法。
root = Root()
conf = {'/' : {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}}
cherrypy.quickstart(root, '/parent', config=conf)
任何帮助都将不胜感激。
答案 0 :(得分:9)
http://tools.cherrypy.org/wiki/RestfulDispatch可能就是你要找的东西。
在CherryPy 3.2中(刚刚发布测试版),将会有一个新的_cp_dispatch
方法,您可以在对象树中使用它来执行相同的操作,甚至可以更改遍历,有点沿着吉诃德的_q_lookup
和_q_resolve
行。见https://bitbucket.org/cherrypy/cherrypy/wiki/WhatsNewIn32#!dynamic-dispatch-by-controllers
答案 1 :(得分:2)
#!/usr/bin/env python
import cherrypy
class Items(object):
exposed = True
def __init__(self):
pass
# this line will map the first argument after / to the 'id' parameter
# for example, a GET request to the url:
# http://localhost:8000/items/
# will call GET with id=None
# and a GET request like this one: http://localhost:8000/items/1
# will call GET with id=1
# you can map several arguments using:
# @cherrypy.propargs('arg1', 'arg2', 'argn')
# def GET(self, arg1, arg2, argn)
@cherrypy.popargs('id')
def GET(self, id=None):
print "id: ", id
if not id:
# return all items
else:
# return only the item with id = id
# HTML5
def OPTIONS(self):
cherrypy.response.headers['Access-Control-Allow-Credentials'] = True
cherrypy.response.headers['Access-Control-Allow-Origin'] = cherrypy.request.headers['ORIGIN']
cherrypy.response.headers['Access-Control-Allow-Methods'] = 'GET, PUT, DELETE'
cherrypy.response.headers['Access-Control-Allow-Headers'] = cherrypy.request.headers['ACCESS-CONTROL-REQUEST-HEADERS']
class Root(object):
pass
root = Root()
root.items = Items()
conf = {
'global': {
'server.socket_host': '0.0.0.0',
'server.socket_port': 8000,
},
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
},
}
cherrypy.quickstart(root, '/', conf)