在Flask中钩子函数是使用特定的装饰器装饰的函数。为什么叫钩子函数呢?是因为钩子函数可以在正常执行的代码中,插入一段自己想要执行的代码。那么这种函数就叫做钩子函数。
before_first_request
部署后处理第一次请求之前执行,当执行第二次的时候,则不会再执行此钩子函数
before_request
在每次请求之前执行。通常可以用这个装饰器来给视图函数增加一些变量,比如下面的例子
template_filter
在使用Jinja2模板时候自定义过滤器。
@app.route('/') def index(): context = { 'article': 'hello, this is test hello world' } return render_template('index.html', **context) @app.template_filter('cut') #把cut函数注册到过滤器中 def cut(value): #value就是使用过滤器的变量 value = value.replace('hello', '') return value #函数的返回值会作为过滤器的返回值
index.html
{{ article|cut }}
context_processor
上下文处理器。返回的