gpt4 book ai didi

python - CherryPy: `error_page.default` 与 `error_page.404` 配置设置之间有什么区别?

转载 作者:行者123 更新时间:2023-12-01 07:26:12 25 4
gpt4 key购买 nike

假设我想显示自己的 404 和 500 页面,到目前为止我发现了两种可能性:

1:使用cherrypy.config.update

def error_page_404(status, message, traceback, version):
return ('Error 404 Page not found')

def error_page_500(status, message, traceback, version):
return ('Error:')

cherrypy.config.update({'error_page.404': error_page_404, 'error_page.500': error_page_500})
  • 使用_cp_config:
  • from cherrypy import _cperror

    def handle_error():
    cherrypy.response.status = 500
    cherrypy.log("handle_error() called. Alarm!", "WEBAPP")
    cherrypy.response.body = ['Sorry, an error occured. The admin has been notified']
    error = _cperror.format_exc()

    def error_page(status, message, traceback, version):
    cherrypy.log("error_page() called. Probably not very important.", "WEBAPP")
    return "Sorry, an error occured."

    class Root:
    _cp_config = {
    'error_page.default': error_page,
    'request.error_response': handle_error
    }

    但是有什么区别或更好的建议吗?

    最佳答案

    request.error_response 允许您设置处理程序来处理一些意外错误,例如您自己从 HTTP 处理程序引发的异常。您为此选项设置的可调用项将根本不接收任何参数,您必须检查 sys.exc_info()欲了解详情,了解到底发生了什么。您还必须自己在错误处理程序中显式设置cherrypy.response.statuscherrypy.response.body

    如果要修改 HTTP 错误代码的错误响应(当引发 cherrypy.HTTPError 实例时,例如 raisecherrypy.NotFound),您可以使用 error_page.default(包罗万象)或 error_page.404(特定于错误)用于处理这些错误。error_page 选项支持文件路径和可调用值。如果使用文件路径,HTML 模板文件可以使用以下替换模式:%(status)s%(message)s%(回溯)s%(版本)s。如果您选择使用函数,它将接收这些函数作为参数 (callback(status, message, traceback, version))。然后,此可调用的返回值将使用 HTTP 响应负载。

    正如您所看到的,这些方法具有不同的含义以及不同级别的灵 active 和可用性。选择对你有用的东西。在内部,默认的 request.error_response 使用 error_page 设置来确定返回的内容。因此,如果您重新定义 request.error_response,它不会使用 error_page.* 设置,除非您明确指定这样做。

    参见the docstring with some explanation here .

    关于python - CherryPy: `error_page.default` 与 `error_page.404` 配置设置之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57436943/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com