2

在带有参数append_slash=True的金字塔中使用notfound_view_config,我在重定向时得到 302 http 状态,但我想设置自定义 http 状态 - 301。

@notfound_view_config(append_slash=True, renderer="not_found.mako") def notfound(request): return {}

4

2 回答 2

2

HTTPFound 似乎是硬编码的AppendSlashNotFoundViewFactory,但您可以使用它的代码作为“未找到视图”的灵感:

from pyramid.interfaces import IRoutesMapper
from pyramid.compat import decode_path_info

@notfound_view_config(renderer="not_found.mako")
def notfound(request):
    path = decode_path_info(request.environ['PATH_INFO'] or '/')
    registry = request.registry
    mapper = registry.queryUtility(IRoutesMapper)
    if mapper is not None and not path.endswith('/'):
        slashpath = path + '/'
        for route in mapper.get_routes():
            if route.match(slashpath) is not None:
                qs = request.query_string
                if qs:
                    qs = '?' + qs
                raise HTTPMovedPermanently(location=request.path+'/'+qs)
    return {}

(未经测试,视为伪代码)

于 2014-07-21T22:44:45.820 回答
1

我不推荐使用的类的解决方案:

class append_slash_notfound_factory(AppendSlashNotFoundViewFactory): def __call__(self, context, request): result = super(append_slash_notfound_factory, self).__call__(context, request) if isinstance(result, HTTPFound): return HTTPMovedPermanently(result.location) return result

于 2014-07-22T08:28:42.630 回答