• 特殊装饰器


    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)
    天道酬勤 循序渐进 技压群雄
  • 相关阅读:
    XML基础总结
    异常处理
    集合总结
    事件源与监听器
    JAVA中的GUI---swing 和awt
    docker搭建wordpress
    Jenkins--第四关_扩展
    docker 安装centos 7
    Jenkins_第五关_系统管理(1)
    Jenkins--第三关_Gitlab安装和配置(续)
  • 原文地址:https://www.cnblogs.com/wuyuan2011woaini/p/14862462.html
Copyright © 2020-2023  润新知