在我的Flask应用程序中,我可以通过为每个错误代码添加错误处理程序装饰器来轻松扩展由单个自定义错误处理程序处理的错误列表
@application.errorhandler(404) @application.errorhandler(401) @application.errorhandler(500) def http_error_handler(error): return flask.render_template('error.html', error=error), error.code然而,这种方法需要为每个错误代码显式装饰器。 有没有办法装饰我(单) http_error_handler函数,以便它处理所有的 HTTP错误?
In my Flask app, I can easily expand the list of errors handled by a single custom error handler by adding errorhandler decorators for each error code as with
@application.errorhandler(404) @application.errorhandler(401) @application.errorhandler(500) def http_error_handler(error): return flask.render_template('error.html', error=error), error.codeHowever this approach requires an explicit decorator for each error code. Is there a way decorate my (single) http_error_handler function so that it handles all HTTP errors?
最满意答案
你不是唯一的解决方法,一个解决方法是指定你正在捕获并绑定到application.error_handler_spec的http错误代码的列表,然后删除装饰器,如下所示:
def http_error_handler(error): return flask.render_template('error.html', error=error), error.code for error in (401, 404, 500): # or with other http code you consider as error application.error_handler_spec[None][error] = http_error_handler我并不理解和丑陋,但它会起作用,我确实希望别人能够提供更好的解决方案。 希望这可以帮助。
You're not the only one, one workaround will be specifying the list of the http error code you're catching and bound to application.error_handler_spec, and drop the decorators, like this:
def http_error_handler(error): return flask.render_template('error.html', error=error), error.code for error in (401, 404, 500): # or with other http code you consider as error application.error_handler_spec[None][error] = http_error_handlerNot ideal and ugly I know, but it will work and I do hope someone else can come with a better solution. Hope this helps.
更多推荐
发布评论