Python Cherrypy 404 Error Handling

I have a web server that has all the configurations installed in the code, but I want to be able to handle all errors on page 404. How do I do this in Python?

+5
source share
3 answers

Make the 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
+5
source

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

+9
source

HTTP

"error_page" HTML- (, 404 Not Found). , . % () s, % () s,% (traceback) s % () 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")}

Starting with version 3.1, you can also provide a function or another that can be written to error_page. It will be given the same status, message, trace, 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 numbered error codes, you can also provide "error_page.default" to handle all codes that do not have their own error_page entry

0
source