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 
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>

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

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

在这里插入图片描述
添加关注,让我们一起共同成长!   

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wu_Candy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值