okuznetsov
okuznetsov

Reputation: 278

How to return HTTPMovedPermanently (301 status) instead HTTPFound (302) in pyramid notfound_view_config

Using notfound_view_config in pyramid with parameter append_slash=True, i get 302 http status when redirecting, but i want set custom http status - 301.

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

Upvotes: 2

Views: 430

Answers (2)

okuznetsov
okuznetsov

Reputation: 278

My solution with deprecated class:

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

Upvotes: 1

Sergey
Sergey

Reputation: 12417

The HTTPFound seems to be hard-coded in AppendSlashNotFoundViewFactory, but you may use its code as an inspiration for your "not found view":

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

(untested, treat as pseudocode)

Upvotes: 2

Related Questions