特殊装饰器

before_request、after_request
from flask import Flask,render_template,redirect
app = Flask(__name__)

"""
before_reuqest = [xxxxxxxxxx1,xxxxxxxxxx2]
"""
@app.before_request
def xxxxxxxxxx1():
    print('前1')

@app.before_request
def xxxxxxxxxx2():
    print('前2')
"""
after_request = [oooooooo1,oooooooo2]
[oooooooo2,oooooooo1,] reversed(after_request)
"""
@app.after_request
def oooooooo1(response):
    print('后1')
    return response

@app.after_request
def oooooooo2(response):
    print('后2')
    return response



@app.route('/x1',methods=['GET','POST'])
def x1():
    print('视图函数x1')
    return "视图函数x1"

@app.route('/x2',methods=['GET','POST'])
def x2():
    print('视图函数x2')
    return "视图函数x2"

if __name__ == '__main__':
    app.__call__
    app.run()
before_request返回
from flask import Flask,render_template,redirect
app = Flask(__name__)

@app.before_request
def xxxxxxxxxx1():
    print('前1')
    return "不要再来烦我了"

@app.before_request
def xxxxxxxxxx2():
    print('前2')

@app.after_request
def oooooooo1(response):
    print('后1')
    return response

@app.after_request
def oooooooo2(response):
    print('后2')
    return response



@app.route('/x1',methods=['GET','POST'])
def x1():
    print('视图函数x1')
    return "视图函数x1"

@app.route('/x2',methods=['GET','POST'])
def x2():
    print('视图函数x2')
    return "视图函数x2"

if __name__ == '__main__':
    app.__call__
    app.run()
before_request实现用户登录
from flask import Flask,render_template,redirect,request,session
app = Flask(__name__)
app.secret_key = 'asdfasdfasdf'
@app.before_request
def check_login():
    if request.path == '/login':
        return None
    user = session.get('user_info')
    if not user:
        return redirect('/login')

@app.route('/login',methods=['GET','POST'])
def login():
    return "视图函数x1"

@app.route('/index',methods=['GET','POST'])
def index():
    print('视图函数x2')
    return "视图函数x2"

if __name__ == '__main__':
    app.run()
errorhandler() 报错返回友好界面
@app.errorhandler(404)
def error404(args):
    print(args)
    return "您访问的页面不存在或者走丢了,,,,,,%s" % (args)
posted @ 2021-06-08 13:50  wuyuan2011woaini  阅读(16)  评论(0编辑  收藏  举报