在CherryPy中使用映射 [英] Using mappings in CherryPy

查看:39
本文介绍了在CherryPy中使用映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调度/其他调度程序" 部分中在CherryPy文档中,有一个Django样式的正则表达式到视图函数映射定义的示例,但没有指示如何将其附加到 cherrypy.tree .

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,
            }
        })

请注意网址格式中的 {argument-name:regular-expression} 语法.

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

是否有一种方法可以使用CherryPy文档中所示的成对列表语法指定路由模式?

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

推荐答案

不需要任何额外的步骤.在请求期间, cherrypy.tree 执行第一个路由阶段,在此阶段,传入请求使用其应用程序路径映射到应用程序.当您在启动时调用 tree.mount(root = None,script_name ='/',config = conf)时,Tree将创建一个cherrypy.Application为您在幕后并将其安装在'/'

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 '/'.

找到该应用程序后,其配置将接管,并且文档中示例应用程序的"request.dispatch"配置将显示对该应用程序中的所有URI使用RoutesDispatcher".然后,该RoutesDispatcher实例会将请求的控制权传递给相应的Controller.

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.

文档中的正则表达式示例甚至还不够完善.您需要编写一个使用它的分派器.该过程仅"需要找到处理程序并收集request.config,但根据所选择的调度方式,这两个活动可能非常复杂.请参阅现有的调度员以获取灵感.

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.

这篇关于在CherryPy中使用映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆