after_request 的文档说“从 Flask 0.7 开始,这个函数可能不会在请求结束时执行,以防发生未处理的异常。”有没有办法改变这一点,以便即使是未处理的异常也会调用 after_request 函数,例如记录回溯?
请您参考如下方法:
使用teardown_request相反。
Register a function to be run at the end of each request, regardless of whether there was an exception or not.
These functions are not allowed to modify the request, and their return values are ignored. If an exception occurred while processing the request, it gets passed to each teardown_request function.
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 时,回溯已经超出范围;只有异常(exception)可用。您可以通过设置 PROPAGATE_EXCEPTIONS = True 来更改它,尽管这可能会产生性能问题。鉴于 Flask 已经记录了回溯,配置日志记录可能比尝试自己记录更容易。
