flask之中间件

一个东西之所以可以加括号,

1.类

2.函数

3.对象

4.方法

中间件举例

from flask import Flask
app = Flask(__name__)
app.secret_key = 'sfergeheh'

@app.route('/x1',methods=['GET','POST'])
def index():
    return 'x1'

class Middleware(object):
    def __init__(self,old_wsgi_app):
        """
        服务端启动时自动执行
        :param old_wsgi_app:
        """
        self.old_wsgi_app = old_wsgi_app

    def __call__(self, environ, start_response):
        """
        每次请求来时
        :param environ:
        :param start_response:
        :return:
        """
        print('before')
        from flask import session,request
        obj = self.old_wsgi_app(environ, start_response)
        print('after')
        return obj
if __name__ == '__main__':
    app.wsgi_app = Middleware(app.wsgi_app) #
    app.run()

    """
    1.执行app.__call__()
    2.调用app.wsgi_app方法
    """

 

posted @ 2018-05-01 11:20  兰博~~  阅读(222)  评论(0编辑  收藏  举报