请求进入函数之前 before_request
- # -*- coding: utf-8 -*-
- from flask import Flask, session, redirect, request
- app = Flask(__name__)
- app.secret_key = '124gt'
- @app.before_request # 请求进入视图函数之前加载
- def be():
- print('before_request....')
- if request.path == '/login':
- return None # 直接略过
- if not session.get('user'):
- return redirect('/login')
- @app.route('/')
- def index():
- print('index')
- return 'index'
- @app.route('/login')
- def login():
- session['user'] = '111134'
- return '登陆成功'
- app.run(host='0.0.0.0', debug=True)
请求视图函数响应客户端之前加载 after_request
- @app.after_request # 请求视图函数响应客户端之前加载
- def af1(args):
- # print(args) # <Response 5 bytes [200 OK]>
- print('after_request...1')
- return args
- @app.after_request
- def af2(args):
- print('after_request...2')
- return args
- @app.after_request
- def af3(args):
- print('after_request...3')
- return args
- @app.route('/')
- def index():
- print('index')
- return 'index'
结果
- index
- after_request...3
- after_request...2
- after_request...1
- 192.168.31.1 - - [09/Dec/2019 06:31:22] "GET / HTTP/1.1" 200 -
before_request和after_request异常情况下返回情况
- @app.before_request # 请求进入视图函数之前加载
- def be1():
- print('before_request....1')
- @app.before_request
- def be2():
- print('before_request....2')
- return '错误' # flask 返回的是HTTPRESPONSE对象
- @app.before_request
- def be3():
- print('before_request....3')
- @app.after_request # 请求视图函数响应客户端之前加载
- def af1(args):
- # print(args) # <Response 5 bytes [200 OK]>
- print('after_request...1')
- return args # 返回的是Response对象
- @app.after_request
- def af2(args):
- print('after_request...2')
- return args # 返回的是Response对象
- @app.after_request
- def af3(args):
- print('after_request...3')
- return args # 返回的是Response对象
- @app.route('/')
- def index():
- print('index')
- return 'index'
结果
after全部返回
- before_request....1
- before_request....2
- after_request...3
- after_request...2
- after_request...1
- 192.168.31.1 - - [09/Dec/2019 06:39:30] "GET / HTTP/1.1" 200 -
页面错误 errorhandler(404)
- # 页面访问错误,找不到的时候,会执行这个装饰函数
- @app.errorhandler(404)
- def error(args):
- print(args)
- return '页面错误'