使用CherryPY MethodDispatcher的动态URL

12 投票
2 回答
6335 浏览
提问于 2025-04-15 15:08

我需要设置一个支持RESTful风格的URL,具体的URL格式如下:

  • /parent/
  • /parent/1
  • /parent/1/children
  • /parent/1/children/1

我想使用MethodDispatcher,这样上面提到的每个URL都可以有GET、POST、PUT和DELETE这些功能。目前我已经让前两个URL工作正常了,但对于“children”部分的配置我还搞不明白。虽然我有相关的书籍,但里面讲得不多,而且我在网上也找不到示例。

这是我现在配置的MethodDispatcher的样子。

root = Root()
conf = {'/' : {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}}    

cherrypy.quickstart(root, '/parent', config=conf)

任何帮助都将非常感谢。

2 个回答

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)
9

http://tools.cherrypy.org/wiki/RestfulDispatch 可能正是你需要的东西。

在 CherryPy 3.2(刚刚结束测试阶段)中,会有一个新的 _cp_dispatch 方法,你可以在你的对象树中使用它来实现相同的功能,甚至可以在访问过程中改变路径,类似于 Quixote 的 _q_lookup_q_resolve。具体可以查看 https://bitbucket.org/cherrypy/cherrypy/wiki/WhatsNewIn32#!dynamic-dispatch-by-controllers

撰写回答