特殊装饰器

Posted wuyuan2011woaini

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了特殊装饰器相关的知识,希望对你有一定的参考价值。

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)

以上是关于特殊装饰器的主要内容,如果未能解决你的问题,请参考以下文章

Adorner 装饰器

Flask特殊装饰器

python-flask复习—— 装饰器的坑及解决办法flask中的路由/实例化配置/对象配置/蓝图/特殊装饰器(中间件重定义错误页面)

Flask--特殊装饰器

装饰器

python-- 类的装饰器方法特殊成员方法