Python Cherrypy 404 Error Handling
Asked Answered
N

3

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?

Noxious answered 8/1, 2010 at 8:50 Comment(1)
Please be more specifc and describe your system in more detail.Aswan
Y
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
Yellowknife answered 8/1, 2010 at 8:58 Comment(2)
How do you send the http 404 header?Hoye
@SeunOsewa cherrypy.response.status = 404Takara
T
9

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

Takara answered 8/1, 2010 at 17:1 Comment(4)
Rather ironically that page is now returning a 404. See here: docs.cherrypy.org/stable/refman/…Writeup
The latest working smnapshot of the original page in archive org: web.archive.org/web/20111016122907/http://www.cherrypy.org/wiki/…Finny
The docs moved once again. For CherryPy 3.2.6 they are located here now: cherrypy.readthedocs.org/en/3.2.6/refman/…Manufacturer
@Manufacturer Don't have permission to view that page :-(.Wynny
Y
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
Yellowknife answered 8/1, 2010 at 8:58 Comment(2)
How do you send the http 404 header?Hoye
@SeunOsewa cherrypy.response.status = 404Takara
M
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

Manufacturer answered 20/1, 2017 at 11:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.