码迷,mamicode.com
首页 > 其他好文 > 详细

特殊装饰器

时间:2021-06-08 23:12:09      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:direct   特殊   auto   登录   als   handle   imp   fir   bar   

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)

特殊装饰器

标签:direct   特殊   auto   登录   als   handle   imp   fir   bar   

原文地址:https://www.cnblogs.com/wuyuan2011woaini/p/14862462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!