Search code examples
pythonhttp-status-code-404pyramidhtml-escape-characters

How to include links in HTTPNotFound errors in Pyramid?


One part of my site is a wiki engine. When a page does not exist I want to provide a custom 404 error page containing a link to create a new page. This custom 404 should only be seen in the context of a failed wiki page view.

To implement this logic I simply return (not raise) a HTTPNotFound() object with a custom message containing a link for the new page creation. Unfortunately the links are escaped. How can I force the html links to appear as links ?

Edit: I found a solution form Python Pyramid & Chameleon templating language escapes html

class Literal:
    def __init__(self, s):
        self.s = s
    def __html__(self):
        return self.s

It's very likely that such an object already exists in Pyramid


Solution

  • Not Found views in Pyramid accept the same predicates as regular views.

    config.add_route('wiki', '/wiki/{page}')
    
    @notfound_view_config()
    def notfound_view(exc, request):
        """ Generic notfound view for the entire site."""
        return exc
    
    @notfound_view_config(route_name='wiki')
    def wiki_notfound_view(exc, request):
        """ Specific notfound for urls matching the wiki pattern."""
        return exc
    

    As far as your escaping issue, that's specific to your templating language. In mako you would use ${ msg | n } and in jinja2 you would use {{ msg | safe }} to turn off auto-escaping on the string.