after_request
的文档说“从Flask 0.7开始,如果发生未处理的异常,可能不会在请求结束时执行此函数。”有没有办法改变这个,所以即使对于未处理的异常,也会调用height:100%
函数,例如记录回溯?
答案 0 :(得分:6)
改为使用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已经记录了回溯,可能更容易配置日志记录而不是尝试自己记录。