如何将塔架中的/ {controller} / {action} / {id}路线移植到金字塔

问题描述

所以我要移植一些旧的Py2 / Pylons应用程序,该应用程序具有https://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/pylons/examples.html第3节中定义的路由,而在Pyramid中是不可能的-那么如何处理?

我对Pylons和Pyramid都不是很熟悉,因此,如果显而易见,我仍然希望获得提示

我有8个控制器,每个控制器有〜2-5个动作,其中只有一些使用{id},我想我需要用单独的route_name装饰每个控制器中的每个动作功能,除了那些不使用任何ID:

@view_defaults(renderer='go.pt',route_name='go')
class GoView:
    def __init__(self,request):
        self.request = request

    @view_config(match_param="action=list")
    def list(self):
        return {'name': 'Go list'}

    @view_config(route_name='go_edit')
    def edit(self):
        return {'name': 'Go edit id: {}'.format(self.request.matchdict["id"])}

    config.add_route("go","/go/{action}"). # deals with all non-id routes pr controller
    config.add_route("go_edit","/go/edit/{id}") # one for each controller+action using id

但是,与Pylons代码相比,我需要添加很多路由-这是犹太金字塔的样式,还是有更好的方法?实际上,即使它为config.add_route生成了更多调用,是否为每个操作添加特定的路由(不管是否使用ID)是否更好?

解决方法

金字塔本身需要精细的路由定义。您可以为此编写帮助程序

def add_action_routes(config,name,path=None):
    if path is None:
        path = name
    if not path.endswith('/'):
        path += '/'
    config.add_route(name,path)
    config.add_route(name + '_action',path + '{action}')
    config.add_route(name + '_id',path + '{action}/{id}')

add_action_routes(config,'go')

然后,您可以根据需要使用view_defaultsview_config将视图连接到这些路线。另一方面,您可以制作自己的网址生成器,以正确处理生成正确格式的网址。

def make_action_url(request,action=None,id=None,**kw):
    if action is None:
        return request.route_url(name,**kw)
    if id is None:
        return request.route_url(name + '_action',action=action,**kw)
    return request.route_url(name + '_id',id=id,**kw)

config.add_request_method(make_action_url,'action_url')

这将使您的代码使用request.action_url(...)生成url,而不会过多地困扰路由名称。