cherrypy - URL dispatcher [duplicate]

烈酒焚心 提交于 2019-12-11 00:20:11

问题


Possible Duplicate:
Using mappings in 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.

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


回答1:


You could use a 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()

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

There is the documentaton from the Routes project.

Or this example from appmecha.



来源:https://stackoverflow.com/questions/13484206/cherrypy-url-dispatcher

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!