Skip to content

Instantly share code, notes, and snippets.

@cfmonkey
Created June 8, 2012 03:21
Show Gist options
  • Select an option

  • Save cfmonkey/2893354 to your computer and use it in GitHub Desktop.

Select an option

Save cfmonkey/2893354 to your computer and use it in GitHub Desktop.
url redirect when it's not found.
from pyramid.renderers import render_to_response
from pyramid.view import notfound_view_config
from pyramid.httpexceptions import HTTPFound, HTTPNotFound
from pyramid.interfaces import IRoutesMapper
def find_route(path, request):
q = request.registry.queryUtility
mapper = q(IRoutesMapper)
if mapper is None:
return False
for route in mapper.get_routes():
match = route.match(path)
if match is not None:
return True
return False
@notfound_view_config()
def notfound(request):
qs = request.query_string
path = request.path
if path.endswith('/'):
r = find_route(path.rstrip('/'), request)
if r is True:
return HTTPFound(location=path.rstrip('/') + qs)
else:
r = find_route(path + '/', request)
if r is True:
return HTTPFound(location=path + '/' + qs)
return HTTPNotFound()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment