Flask特殊的装饰器(重要)
程序员文章站
2022-06-22 16:40:19
文章目录(1)before_request 与 after_requestapp = Flask(__name__)app.config.from_object('settings.DevelopmentConfig') # 引入配置文件@app.before_requestdef test1(): print('before_request')@app.after_requestdef test2(response): print('after_request')....
文章目录
(1)before_request 与 after_request
app = Flask(__name__)
app.config.from_object('settings.DevelopmentConfig') # 引入配置文件
@app.before_request
def test1():
print('before_request')
@app.after_request
def test2(response):
print('after_request')
return response
@app.route('/index')
def index():
print('index')
return 'index'
@app.route('/login')
def login():
print('login')
return 'login'
if __name__ == '__main__':
app.run()
'''
before_request
index
after_request
'''
@app.before_request
def test1():
print('before_request_01')
@app.before_request
def test2():
print('before_request_02')
@app.after_request
def test3(response):
print('after_request_01')
return response
@app.after_request
def test4(response):
print('after_request_02')
return response
@app.route('/index')
def index():
print('index')
return 'index'
@app.route('/login')
def login():
print('login')
return 'login'
if __name__ == '__main__':
app.run()
'''
before_request_01
before_request_02
index
after_request_02
after_request_01
'''
如果 test1 函数有返回值,不执行 test2。
@app.before_request
def test1():
print('before_request_01')
return ''
@app.before_request
def test2():
print('before_request_02')
@app.after_request
def test3(response):
print('after_request_01')
return response
@app.after_request
def test4(response):
print('after_request_02')
return response
@app.route('/index')
def index():
print('index')
return 'index'
@app.route('/login')
def login():
print('login')
return 'login'
if __name__ == '__main__':
app.run()
'''
before_request_01
after_request_02
after_request_01
'''
flask和<=django1.9会执行所有的response返回,但是django1.10及之后的版本会这样执行:
(2) before_first_request
第一次请求的时候才执行,
@app.before_first_request
def test():
print('test')
@app.route('/index')
def index():
return 'index'
(3)template_global 与 template_filter
模板中有介绍,在这里不赘述。
(4) errorhandler(应用比较广)
@app.errorhandler(404)
def page_not_found(arg):
return 'This page does not exit'
@app.route('/index')
def index():
return 'index'
if __name__ == '__main__':
app.run()
本文地址:https://blog.csdn.net/Thanlon/article/details/107272287