在带有参数append_slash=True的金字塔中使用notfound_view_config,我在重定向时得到 302 http 状态,但我想设置自定义 http 状态 - 301。
@notfound_view_config(append_slash=True, renderer="not_found.mako")
def notfound(request):
return {}
在带有参数append_slash=True的金字塔中使用notfound_view_config,我在重定向时得到 302 http 状态,但我想设置自定义 http 状态 - 301。
@notfound_view_config(append_slash=True, renderer="not_found.mako")
def notfound(request):
return {}
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 {}
(未经测试,视为伪代码)
我不推荐使用的类的解决方案:
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