cherrypy-URL调度程序
问题描述:
可能重复:
在CherryPy中使用映射
我如何将URL regEx(例如/data/[A-Z].txt)映射到cherrypy中的资源?那里有一个简单的例子吗?我在这里没有文档.
How would I map a url regEx such as /data/[A-Z].txt to a resource in cherrypy? Is there an simple example somewhere? I don't get the docs here.
答
您可以使用 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命令:
You might test this with a browser on http://127.0.0.1:5000/surbiton You can test the POST command with curl:
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项目中的文档.
或者来自 appmecha 的示例.