Flask Werkzeug工具包

Werkzeug是一个WSGI工具包,他可以作为一个Web框架的底层库。 werkzeug 不是一个web服务器,也不是一个web框架,而是一个工具包,官方的介绍说是一个 WSGI 工具包,它可以作为一个 Web 框架的底层库,因为它封装好了很多 Web 框架的东西,例如 Request,Response 等等 。

from werkzeug.wrappers import Request, Response

@Request.application
def hello(request):
    return Response('Hello World!')

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 4000, hello)

flask正是依赖于这个werkzeug模块,由wekzeug模块实现了socket服务端的功能,hello必然是加括号运行了,才会执行hello里面的代码,而在flask中app.run()会调用run_simple(host, port, self, **options)把上面代码例子的hello替换成了self也就是app。app()会触发Flask类的__call__方法。

所以flask程序的入口就在__call__方法中,而__call__方法返回self.wsgi_app(environ, start_response),所以整个程序的执行过程都在 self.wsgi_app(environ, start_response)中.

总:

1 app.run() 调用 werkzeug.serving的run_simple(host, port, self, **options)
2 self()等价于app(), app()调用Flask类的__call__方法
3 Flask类的__call__方法返回了 self.wsgi_app(environ, start_response)
4 flask程序的执行过程都在 self.wsgi_app(environ, start_response)中

app.run()具体源码:

def run(self, host=None, port=None, debug=None,
            load_dotenv=True, **options):
       
    	 ...
        
         _host ='127.0.0.1'
         _port = 5000
        
         ...
            
         host = host or sn_host or _host
         port = int(port or sn_port or _port)
            
         ...
    
         from werkzeug.serving import run_simple

            try:
                run_simple(host, port, self, **options)
            finally:
                # reset the first request information if the development server
                # reset normally.  This makes it possible to restart the server
                # without reloader and that stuff from an interactive shell.
                self._got_first_request = False
    ...
    
    def __call__(self, environ, start_response):
        """The WSGI server calls the Flask application object as the
        WSGI application. This calls :meth:`wsgi_app` which can be
        wrapped to applying middleware."""
        return self.wsgi_app(environ, start_response)
    ...
    
    def wsgi_app(self, environ, start_response):
        
        ctx = self.request_context(environ)
        error = None
        try:
            try:
                ctx.push()
                response = self.full_dispatch_request()
            except Exception as e:
                error = e
                response = self.handle_exception(e)
            except:
                error = sys.exc_info()[1]
                raise
            return response(environ, start_response)
        finally:
            if self.should_ignore_error(error):
                error = None
            ctx.auto_pop(error)
   ...
关键词:
  • Werkzeug是一个WSGI工具包,本质上是一个socket服务端。
  • flask基于Werkzeug,flask只保留了web开发的核心功能。
  • flask的执行过程都在def wsgi_app(self, environ, start_response):中
posted @ 2020-07-21 11:46  小渣猫  阅读(281)  评论(0)    收藏  举报