Pyramid 中带有斜线的路径 [英] Routes with trailing slashes in Pyramid

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

问题描述

假设我有一条路线/foo/bar/baz".我还想有另一个对应于/foo"或/foo/"的视图.但我不想系统地为其他路由添加尾部斜杠,仅用于/foo 和其他一些路由(/buz 但不是/biz)

Let's say I have a route '/foo/bar/baz'. I would also like to have another view corresponding to '/foo' or '/foo/'. But I don't want to systematically append trailing slashes for other routes, only for /foo and a few others (/buz but not /biz)

据我所知,我不能简单地定义两条具有相同 route_name 的路由.我目前这样做:

From what I saw I cannot simply define two routes with the same route_name. I currently do this:

config.add_route('foo', '/foo')
config.add_route('foo_slash', '/foo/')
config.add_view(lambda _,__: HTTPFound('/foo'), route_name='foo_slash')

在 Pyramid 中有什么更优雅的东西可以做到这一点吗?

Is there something more elegant in Pyramid to do this ?

推荐答案

当我为我的项目寻找相同的东西时找到了这个解决方案

Found this solution when I was looking for the same thing for my project

def add_auto_route(config,name, pattern, **kw):
    config.add_route(name, pattern, **kw)
    if not pattern.endswith('/'):
        config.add_route(name + '_auto', pattern + '/')
        def redirector(request):
            return HTTPMovedPermanently(request.route_url(name))
        config.add_view(redirector, route_name=name + '_auto')

然后在路由配置期间,

add_auto_route(config,'events','/events')

而不是config.add_route('events','/events')

基本上它是您的方法的混合.定义了名称以 _auto 结尾的新路由,其视图重定向到原始路由.

Basically it is a hybrid of your methods. A new route with name ending in _auto is defined and its view redirects to the original route.

编辑

该解决方案没有考虑动态 URL 组件和 GET 参数.对于像 /abc/{def}?m=aasa 这样的 URL,使用 add_auto_route() 会抛出一个关键错误,因为 redirector 函数会不考虑 request.matchdict.下面的代码就是这样做的.要访问 GET 参数,它还使用 _query=request.GET

The solution does not take into account dynamic URL components and GET parameters. For a URL like /abc/{def}?m=aasa, using add_auto_route() will throw a key error because the redirector function does not take into account request.matchdict. The below code does that. To access GET parameters it also uses _query=request.GET

def add_auto_route(config,name, pattern, **kw):
    config.add_route(name, pattern, **kw)
    if not pattern.endswith('/'):
        config.add_route(name + '_auto', pattern + '/')
        def redirector(request):
            return HTTPMovedPermanently(request.route_url(name,_query=request.GET,**request.matchdict))
        config.add_view(redirector, route_name=name + '_auto')

这篇关于Pyramid 中带有斜线的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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