William Troup
William Troup

Reputation: 13131

Python Cherrypy 404 Error Handling

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?

Upvotes: 5

Views: 8548

Answers (3)

e1i45
e1i45

Reputation: 1589

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

Upvotes: 0

fumanchu
fumanchu

Reputation: 14559

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

Upvotes: 9

aatifh
aatifh

Reputation: 2337

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

Upvotes: 6

Related Questions