Python + Flask 常用的钩子函数

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 
 1 from flask import Flask,request,render_template,abort,jsonify
 2  
 3 app = Flask(name)
 4 error_list=[]
 5  
 6 @app.route('/')
 7 def index():
 8 ### print(1/0)
 9 ### abort(404) #我们可以使用flask.abort手动抛出相应的错误
10     return render_template("index.html")
11  
12 @app.route('/user')
13 def user():
14     user_agent = request.headers.get("User-Agent")
15     return f"<h1>Hello World!</h1>
Hello World!{user_agent}"
16  
17 @app.route('/commit')
18 def commit():
19     return '<form action="/getUser" method="get">  ' 
20            '<input type="text" name="username" value="">  ' 
21            '<input type="submit" value="提交">  ' 
22            '</form>'
1 @app.before_first_request
2 def before_first_request():
3     print("call the before first request of function")
1 @app.before_request
2 def before_request():
3     print("call the before request of function")
1 @app.after_request
2 def after_request(response):
3     print("call the after request of function")
4     ### print(response.get_json())
5     ### print(response.data)
6     print(response.headers)
7     ### return jsonify({"a": 1})
8     return response
1 @app.teardown_request
2 def teardown_request(error):
3     print("call the teardown request of function")
4     print("the error is:",error)
5     error_list.append(error)
1 @app.teardown_appcontext
2 def teardown_appcontext(exception=None):
3     print("call the teardown appcontext of function")
4     if(exception is None):
5         print("None")
6     else:
7         print("the exception is:",exception)
8         ### db.close();
9         ### file.close()
1 @app.route("/get_error")
2 def get_error():
3     print(error_list)
4     return str(error_list)
1 @app.template_filter("update")
2 def upper_filter(str):
3     print("call the upper filter of function")
4     return str.upper()+" good good study"
1 @app.context_processor
2 def context_process():
3     print("call the context process of function")
4     content = 'flask context manager'
5     return dict(content=content)
1 @app.errorhandler(500)
2 def server_is_exception(error):
3     print("*"*100)
4     print(error)
5     return 'the server is exception',500
1 @app.errorhandler(404)
2 def page_not_found(error):
3     print("*" * 50)
4     print(error)
5     return 'This page does not exist',404
6  
7 if __name__ == __'main'__:
8     app.run()

备注:

在 Python 文件所在目录创建一个 templates 目录, 放入 index.html 文件,文件内容如下。

index.html文件内容

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <!--<h2>{{ content }}</h2>-->
 9 <h1>the content = {{ content |update }}</h1>
10 </body>
11 </html>

欢迎关注【无量测试之道】公众号,回复【领取资源】
Python编程学习资源干货、
Python+Appium框架APP的UI自动化、
Python+Selenium框架Web的UI自动化、
Python+Unittest框架API自动化、
资源和代码 免费送啦~
文章下方有公众号二维码,可直接微信扫一扫关注即可。

备注:我的个人公众号已正式开通,致力于测试技术的分享,包含:大数据测试、功能测试,测试开发,API接口自动化、测试运维、UI自动化测试等,微信搜索公众号:“无量测试之道”,或扫描下方二维码:


添加关注,让我们一起共同成长!

原文地址:https://www.cnblogs.com/Wu13241454771/p/15439350.html