1.名词解释
钩子函数是指在执行函数和目标函数之间挂载的函数,框架开发者给调用方提供一个point-挂载点,至于挂载什么函数由调用方决定。
@before_first_request
在对应用程序实例的第一个请求之前注册要运行的函数,只会运行一次。
@before_request
在每个请求之前注册一个要运行的函数,每一次请求都会执行一次。
@after_request
在每个请求之后注册一个要运行的函数,每次请求完成后都会执行。需要接收一个 Response 对象作为参数,并返回一个新的 Response 对象,或者返回接收的 Response 对象。
@teardown_request
注册在每一个请求的末尾,不管是否有异常,每次请求的最后都会执行。
@context_processor
上下文处理器,返回的字典可以在全部的模板中使用。
@template_filter('upper')
增加模板过滤器,可以在模板中使用该函数,后面的参数是名称,在模板中用到。
@errorhandler(400)
发生一些异常时,比如404,500,或者抛出异常(Exception)之类的,就会自动调用该钩子函数。
1.发生请求错误时,框架会自动调用相应的钩子函数,并向钩子函数中传入error参数。
2.如果钩子函数没有定义error参数,就会报错。
3.可以使用abort(http status code)函数来手动终止请求抛出异常,如果要是发生参数错误,可以abort(404)之类的。
@teardown_appcontext
不管是否有异常,注册的函数都会在每次请求之后执行。
flask 为上下文提供了一个 teardown_appcontext 钩子,使用它注册的毁掉函数会在程序上下文被销毁时调用,通常也在请求上下文被销毁时调用。
比如你需要在每个请求处理结束后销毁数据库连接:app.teardown_appcontext 装饰器注册的回调函数需要接收异常对象作为参数,当请求被正常处理时这个参数将是None,这个函数的返回值将被忽略。
2.代码演示
常见的 http status code:
200 --OK
302 --Move Temporarily
400 --bad request
401 --Unauthorized
403 --forbidden
404 --not found
500 --interal server error
from flask import Flask,request,render_template,abort,jsonify
app = Flask(name)
error_list=[]
@app.route('/')
def index():
### print(1/0)
### abort(404) #我们可以使用flask.abort手动抛出相应的错误
return render_template("index.html")
@app.route('/user')
def user():
user_agent = request.headers.get("User-Agent")
return f"<h1>Hello World!</h1>\nHello World!{user_agent}"
@app.route('/commit')
def commit():
return '<form action="/getUser" method="get"> ' \
'<input type="text" name="username" value=""> ' \
'<input type="submit" value="提交"> ' \
'</form>'
@app.before_first_request
def before_first_request():
print("call the before first request of function")
@app.before_request
def before_request():
print("call the before request of function")
@app.after_request
def after_request(response):
print("call the after request of function")
### print(response.get_json())
### print(response.data)
print(response.headers)
### return jsonify({"a": 1})
return response
@app.teardown_request
def teardown_request(error):
print("call the teardown request of function")
print("the error is:",error)
error_list.append(error)
@app.teardown_appcontext
def teardown_appcontext(exception=None):
print("call the teardown appcontext of function")
if(exception is None):
print("None")
else:
print("the exception is:",exception)
### db.close();
### file.close()
@app.route("/get_error")
def get_error():
print(error_list)
return str(error_list)
@app.template_filter("update")
def upper_filter(str):
print("call the upper filter of function")
return str.upper()+" good good study"
@app.context_processor
def context_process():
print("call the context process of function")
content = 'flask context manager'
return dict(content=content)
@app.errorhandler(500)
def server_is_exception(error):
print("*"*100)
print(error)
return 'the server is exception',500
@app.errorhandler(404)
def page_not_found(error):
print("*" * 50)
print(error)
return 'This page does not exist',404
if __name__ == __'main'__:
app.run()
备注:
在 Python 文件所在目录创建一个 templates 目录, 放入 index.html 文件,文件内容如下。
index.html文件内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--<h2>{{ content }}</h2>-->
<h1>the content = {{ content |update }}</h1>
</body>
</html>
end
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有