说明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')
Run Code Online (Sandbox Code Playgroud)
请注意,在teardown_request调用时,跟踪已经超出范围; 只有异常可用.您可以通过设置更改此设置PROPAGATE_EXCEPTIONS = True,但这可能会出现性能问题.鉴于Flask已经记录了回溯,可能更容易配置日志记录而不是尝试自己记录.
| 归档时间: |
|
| 查看次数: |
1394 次 |
| 最近记录: |