Динамический URL-адрес с помощью метода CherryPY MethodDispatcher
Мне нужно настроить URL-адрес стиля RESTful, который поддерживает следующую схему URL:
- /parent/
- /parent/1
- /родитель/1/дети
- /родитель/1/Детский/1
Я хочу использовать MethodDispatcher, чтобы каждый из вышеперечисленных мог иметь функции GET/POST/PUT/DELETE. Я работаю для первого и второго, но не могу понять, как настроить диспетчер для дочерней части. У меня есть книга, но она едва охватывает это, и я не могу найти какой-либо образец в Интернете.
Вот как я сейчас настроил MethodDispatcher.
root = Root()
conf = {'/' : {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}}
cherrypy.quickstart(root, '/parent', config=conf)
Любая помощь будет оценена.
Ответы
Ответ 1
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
Ответ 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)