金字塔路由到 class 方法

Pyramid routing to class methods

pyramid documentation 开始,在配置器的 add_view 上存在一个 attr 参数,它指出:

The attr value allows you to vary the method attribute used to obtain the response. For example, if your view was a class, and the class has a method named index and you wanted to use this method instead of the class' __call__ method to return the response, you'd say attr="index" in the view configuration for the view.

考虑到这一点,我想将 /myrequest 下的所有请求路由到 class MyRequest。鉴于以下 class:

@view_defaults(renderer='json')
class MyHandler(object):
    def __init__(self, request):
        self.request = request

    def start(self):
        return {'success': True}

    def end(self):
        return {'success': True}

这似乎是在配置中执行此操作的方法,添加以下行:

config.add_view(MyHandler, '/myrequest', attr='start')
config.add_view(MyHandler, '/myrequest', attr='end')

等等,对于我想要在 MyHandler 下路由的所有方法。不幸的是,这不起作用。执行此操作的正确方法似乎是:

config.add_route('myroutestart', '/myroute/start')
config.add_route('myrouteend', '/myroute/end')
config.add_view(MyHandler, attr='start', route_name='myroutestart')
config.add_view(MyHandler, attr='end', route_name='myrouteend')

这似乎是很多样板文件。有没有办法将每条路线减少到 1 行?或者更理想的是,每个 class?

一行

金字塔社区指南 v0.2 中 Route and View Examples 中的示例 #4,Pyramid for Pylons Users,提供以下内容。

# Pyramid
config.add_route("help", "/help/{action}")

@view_config(route_name="help", match_param="action=help", ...)
def help(self):   # In some arbitrary class.
    ...

虽然这本食谱提到 pyramid_handlers 作为执行此操作的一种选择,但 Pyramid 的一位维护者的文章 "Outgrowing Pyramid Handlers" 鼓励使用 Pyramid 的配置。