3.5 Your Own 404 Handler

In some cases, you may wish to return a 404 (HTTP_NOT_FOUND) or other non-200 result from your handler. There is a trick here. if you return HTTP_NOT_FOUND from your handler, Apache will handle rendering an error page. This can be problematic if you wish your handler to render it's own error page.

In this case, you need to set req.status = apache.HTTP_NOT_FOUND, render your page, and then return(apache.OK):

   from mod_python import apache

   def handler(req):
      if req.filename[-17:] == 'apache-error.html':
         #  make Apache report an error and render the error page
      if req.filename[-18:] == 'handler-error.html':
         #  use our own error page
         req.status = apache.HTTP_NOT_FOUND
         pagebuffer = 'Page not here.  Page left, not know where gone.'
         #  use the contents of a file
         pagebuffer = open(req.filename, 'r').read()

      #  fall through from the latter two above

Note that if wishing to returning an error page from a handler phase other than the response handler, the value apache.DONE must be returned instead of apache.OK. If this is not done, subsequent handler phases will still be run. The value of apache.DONE indicates that processing of the request should be stopped immediately. If using stacked response handlers, then apache.DONE should also be returned in that situation to prevent subsequent handlers registered for that phase being run if appropriate.