钩子函数的两种应用:
(1). 应用在app上
before_first_request
before_request
after_request
teardown_request
(2). 应用在蓝图上
before_app_first_request #只会在第一次请求执行,往后就不执行, (待定,此属性没调试通过)
before_app_request # 每次请求都会执行一次(重点)
after_app_request # 每次响应返回都会执行
teardown_app_request # 每次请求响应结束后执行,收尾
代码实例:
# 应用在app上的钩子函数required_login_list = ["/user/center","/user/change","/article/publish",'/user/upload_photo','/user/photo_del','/article/add_comment','/user/aboutme',"/user/showabout", ]# 每次请求都会执行一次(重点)
@user_bp1.before_app_request
def first_reqeust():print("before_app_request", request.path)if request.path in required_login_list:id = session.get("uid")if not id:return render_template('users/login.html')else:user = User.query.get(id)# g对象, 本次请求的对象;本次请求的全局对象,过了本次就失效g.user = user# 每次响应返回都会执行
@user_bp1.after_app_request
def after_request_test(response):response.set_cookie("a", "bbb", max_age=19)print("after_app_request")return response# 每次请求响应结束后执行,收尾
@user_bp1.teardown_app_request
def teardown_request_test(response):print("teardown_request_test")return response
(1). 设置钩子函数,请求指定路径时校验session
(2). 登录页面设置session