Using mappings in CherryPy

北城以北 提交于 2019-12-02 03:41:28

问题


In the "Dispatching / Other Dispatchers" section of the CherryPy documentation, there is an example of Django-style regular-expression-to-view-function mapping definition, but there is no indication on how to attach this to cherrypy.tree.

How are you supposed to register this mapping?

Edit: Based on the "regex URL mapping" thread in the cherrypy-users Google group, I could figure out that to attach views using regular expressions, you need to use routes-style mapping using the cherrypy.dispatch.RoutesDispatcher class like so:

def hello(name='stranger'):
    """Sample view."""
    return 'Hello, %s!'%name

dispatch = cherrypy.dispatch.RoutesDispatcher()
dispatch.connect('hello-1', '/hello', hello)
dispatch.connect('hello-2', '/hello/{name:([^/]+)}', hello)
cherrypy.tree.mount(None, config={
        '/': {
             'request.dispatch': dispatch,
            }
        })

Note the {argument-name:regular-expression} syntax in the URL pattern.

Is there a way to specifiy the route patterns using the list-of-pairs syntax as shown in the CherryPy documentation?


回答1:


There's not any extra step required. During a request, cherrypy.tree performs a first routing stage, where the incoming request is mapped to an Application using its path-to-app mapping. When you call tree.mount(root=None, script_name='/', config=conf) at startup, the Tree creates a cherrypy.Application for you behind the scenes and mounts it at '/'.

Once the Application is found, its config takes over, and the "request.dispatch" config for the example app in the docs says "use the RoutesDispatcher for all URI's in this app". That RoutesDispatcher instance will then pass control of the request to the appropriate Controller.

The regex example in the docs isn't even that well-developed. You'd need to write a Dispatcher which uses it. That process "only" needs to find the handler and collect request.config, but those two activities can be very complex depending on the dispatch style chosen. See the existing dispatchers for inspiration.



来源:https://stackoverflow.com/questions/11142625/using-mappings-in-cherrypy

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