5

I have a web server that has all of the configurations set in the code, but I want to be able to handle all page 404 errors. How would I go about doing this in Python?

William Troup
  • 12,739
  • 21
  • 70
  • 98

3 Answers3

9

See also http://www.cherrypy.org/wiki/ErrorsAndExceptions#AnticipatedHTTPresponses if you want more traditional replacement of 4xx and 5xx output.

fumanchu
  • 14,419
  • 6
  • 31
  • 36
  • 21
    Rather ironically that page is now returning a 404. See here: http://docs.cherrypy.org/stable/refman/_cperror.html?highlight=exception#anticipated-http-responses – OrganicPanda Nov 18 '11 at 14:21
  • 1
    The latest working smnapshot of the original page in archive org: http://web.archive.org/web/20111016122907/http://www.cherrypy.org/wiki/ErrorsAndExceptions – Alojz Janez Apr 23 '14 at 18:22
  • The docs moved once again. For CherryPy 3.2.6 they are located here now: https://cherrypy.readthedocs.org/en/3.2.6/refman/_cperror.html#anticipated-http-responses – e1i45 Oct 09 '14 at 12:52
  • @e1i45 Don't have permission to view that page :-(. – Keeely Jan 16 '17 at 18:01
6

Make a default handler in the root.

class Root:
    def index(self):
        return "Hello!"
    index.exposed = True

    def default(self, attr='abc'):
        return "Page not Found!"
    default.exposed = True
aatifh
  • 2,317
  • 4
  • 27
  • 30
0

Anticipated HTTP responses

The 'error_page' config namespace can be used to provide custom HTML output for expected responses (like 404 Not Found). Supply a filename from which the output will be read. The contents will be interpolated with the values %(status)s, %(message)s, %(traceback)s, and %(version)s using plain old Python string formatting <http://www.python.org/doc/2.6.4/library/stdtypes.html#string-formatting-operations>_.

::

_cp_config = {'error_page.404': os.path.join(localDir, "static/index.html")}

Beginning in version 3.1, you may also provide a function or other callable as an error_page entry. It will be passed the same status, message, traceback and version arguments that are interpolated into templates::

def error_page_402(status, message, traceback, version):
    return "Error %s - Well, I'm very sorry but you haven't paid!" % status
cherrypy.config.update({'error_page.402': error_page_402})

Also in 3.1, in addition to the numbered error codes, you may also supply "error_page.default" to handle all codes which do not have their own error_page entry

e1i45
  • 1,519
  • 1
  • 14
  • 20