after_request的文档说:“从Flask 0.7开始,如果发生未处理的异常,此功能可能不会在请求结束时执行。”有没有一种方法可以更改此方法,以便即使对于未处理的异常(例如记录回溯)也调用after_request函数?

最佳答案

使用teardown_request代替。


  注册一个要在每个请求结束时运行的函数,而不管是否存在异常。
  
  不允许这些函数修改请求,并且它们的返回值将被忽略。如果在处理请求时发生异常,它将被传递给每个teardown_request函数。


from flask import Flask

app = Flask(__name__)
# unhandled teardown won't happen while in debug mode
# app.debug = True
# set this if you need the full traceback, not just the exception
# app.config['PROPAGATE_EXCEPTIONS'] = True

@app.route('/')
def index():
    print(test)

@app.teardown_request
def log_unhandled(e):
    if e is not None:
        print(repr(e))
        # app.logger.exception(e)  # only works with PROPAGATE_EXCEPTIONS

app.run('localhost')


请注意,在调用teardown_request时,回溯已经超出范围。只有例外可用。您可以通过设置PROPAGATE_EXCEPTIONS = True来更改此设置,尽管这可能会导致性能问题。鉴于该追溯已由Flask记录,因此配置日志记录可能比尝试自己记录日志更容易。

10-06 05:22
查看更多