flask: 请求钩子
一,有哪些钩子函数?
1、app.before_request:在每次请求之前运行
2、app.after_request:如果没有未处理的异常抛出,在每次请求后运行(视图函数正常退出)
3、app.teardown_request:每次请求后运行,即使有未处理的异常抛出

二,例子:
代码:
@app.before_request
def handle_before_request():
# 在每次请求处理之前被执行
print("handle_before_request is running")
@app.after_request
def handle_after_request(response):
# 在每次请求(视图函数)处理之后都被执行,前提是视图函数没有异常
# 在请求之后,会接收一个参数,这个参数是前面的请求处理完毕后返回
# 的响应数据,如果需要对响应做额外处理,可以在这里进行
print(f"handle_after_request is running, the response is {response}")
return response
@app.teardown_request
def handle_teardown_request(response):
# 在每次请求(视图函数)处理之后都会被执行,无论视图函数是否异常
# 每一次请求之后都会调用,会接收一个参数,这个参数是服务器出现的
# 错误信息,工作在非调试模式下,当时图函数出现异常时,才会被执行
print(f"handle_teardown_request is running, the response is {response}")
"""
if request.path == url_for("index"):
print("在请求钩子中判断请求的视图逻辑:index")
elif request.path == url_for("hello"):
print("在请求钩子中判断请求的视图逻辑:hello")
"""
return response
运行结果:
$ flask run
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
handle_before_request is running
handle_after_request is running, the response is <Response 451 bytes [200 OK]>
handle_teardown_request is running, the response is None
127.0.0.1 - - [11/Nov/2025 14:31:28] "GET /photo/upload/ HTTP/1.1" 200 -
浙公网安备 33010602011771号