Как вернуть HTTPMovedPermanently (статус 301) вместо HTTPFound (302) в пирамиде notfound_view_config

Используя notfound_view_config в пирамиде с параметром append_slash = True, я получаю 302 статуса http при перенаправлении, но я хочу установить пользовательский статус http - 301.

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

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 {}

(не проверено, рассматривается как псевдокод)

Мое решение с устаревшим классом:

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

Другие вопросы по тегам