cherrypy - URL调度程序

时间:2012-11-20 23:48:45

标签: cherrypy

  

可能重复:
  Using mappings in CherryPy

如何将一个url regEx(例如/data/[A-Z].txt)映射到cherrypy中的资源?某个地方有一个简单的例子吗?我没有在这里获得文档。

http://tools.cherrypy.org/wiki/RestfulDispatch

1 个答案:

答案 0 :(得分:3)

您可以使用RoutesDispatcher

import cherrypy

class City:
    def __init__(self, name):
        self.name = name
        self.population = 10000

    @cherrypy.expose
    def index(self, **kwargs):
        return "Welcome to %s, pop. %s" % (self.name, self.population)

    @cherrypy.expose
    def update(self, **kwargs):
        self.population = kwargs['pop']
        return "OK"

d = cherrypy.dispatch.RoutesDispatcher()
d.connect(action='index', name='hounslow', route='/hounslow', controller=City('Hounslow'))
d.connect(action='index', name='surbiton', route='/surbiton', controller=City('Surbiton'),
          conditions=dict(method=['GET']))
d.mapper.connect('/surbiton', controller='surbiton',
                 action='update', conditions=dict(method=['POST']))

conf = {'/': {'request.dispatch': d}}
cherrypy.config.update({'server.socket_port': 5000})
cherrypy.tree.mount(root=None, config=conf)
cherrypy.engine.start()

您可以使用http://127.0.0.1:5000/surbiton上的浏览器对此进行测试 您可以使用curl测试POST命令:

curl -i -X GET http://127.0.0.1:5000/surbiton
curl -i -d "pop=100" -X POST http://127.0.0.1:5000/surbiton
curl -i -X GET http://127.0.0.1:5000/surbiton

来自Routes project的文档。

appmecha中的此示例。