开发者

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 Pyt开发者_如何学Pythonhon?


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜