01 flask源码剖析之werkzurg 了解wsgi

01 werkzurg了解wsgi

1. wsgi

django和flask内部都没有实现socket,而是wsgi实现。
wsgi是web服务网关接口,他是一个协议,实现它的协议的有:wsgiref/werkzurg/uwsgi

  1. django之前

    from wsgiref.simple_server import make_server
     
    def run(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ]
     
    if __name__ == '__main__':
        httpd = make_server('127.0.0.1', 8000, run)
        httpd.serve_forever()
    
  2. flask之前

    from werkzeug.serving import run_simple
    from werkzeug.wrappers import BaseResponse
    
    
    def func(environ, start_response):
        print('请求来了')
        response = BaseResponse('你好')
        return response(environ, start_response)
    
    
    if __name__ == '__main__':
        run_simple('127.0.0.1', 5000, func)
    

2. flask之werkzurg源码流程

  1. 程序启动之app.run()

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/index')
    def index():
        return 'hello world'
    
    if __name__ == '__main__':
        app.run()
    
  2. 执行里边run_simple方法的第三个参数加括号

    def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):
          from werkzeug.serving import run_simple
          run_simple(host, port, self, **options)
    
  3. 触发执行__call__方法,然后去执行wsgi_app方法

    def __call__(self, environ, start_response):
    	return self.wsgi_app(environ, start_response)
    
  4. 执行wsgi_app方法里边的full_dispatch_request方法

    def wsgi_app(self, environ, start_response):
    	response = self.full_dispatch_request()
    	return response(environ, start_response)
    

    full_dispatch_request

    def full_dispatch_request(self):
        return self.finalize_request(rv)
    
  5. 执行finalize_request方法,携带rv参数,rv为视图的返回值

    def finalize_request(self, rv, from_error_handler=False):
        response = self.make_response(rv)
        return response
    
  6. 执行finalize_request方法里边的make_response方法

    def make_response(self, rv):
    	if not isinstance(rv, self.response_class):
             if isinstance(rv, (text_type, bytes, bytearray)):
                 rv = self.response_class(rv, status=status, headers=headers)
                 return rv
    
  7. response_class

    • response_class=Response
    • Response继承werkzurg的BaseResponse

3. 总结

  • 请求过来,经过一系列,最后由BaseResponse返回
from werkzeug.serving import run_simple
from werkzeug.wrappers import BaseResponse

def func(environ, start_response):
    print('请求来了')
    response = BaseResponse('你好')
    return response(environ, start_response)


if __name__ == '__main__':
    run_simple('127.0.0.1', 5000, func)
posted @ 2019-11-25 20:00  LBZHK  阅读(287)  评论(0编辑  收藏  举报