所以我正在移植一些旧的Py2/Pylons应用程序,它的路由定义在https://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/pylons/examples.html第3节中,这在金字塔中是不可能的-那么该如何处理呢?
我既不熟悉塔架,也不熟悉金字塔,所以如果很明显的话,我还是想要一个提示。
我有8个控制器,每个控制器有2-5个动作,其中只有一些使用了{id},我想我需要用单独的route_names来装饰每个控制器中的每个动作函数,除了那些不使用任何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代码相比,我需要添加相当多的路线-这是犹太金字塔风格,还是有更好的方法?实际上,为每个操作添加特定的路由是否更好,无论它是否使用ID,即使它生成更多对config.add_route的调用?
发布于 2020-10-02 00:07:51
金字塔本身需要细粒度的路由定义。你可以这样写帮助器
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_defaults和view_config将视图连接到这些路由。另一方面,您可以制作自己的url生成器,它可以正确地处理生成正确格式的url。
def make_action_url(request, name, 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', action=action, id=id, **kw)
config.add_request_method(make_action_url, 'action_url')这将允许您的代码使用request.action_url(...)生成urls,而无需过多考虑路由名称。
https://stackoverflow.com/questions/63978101
复制相似问题