about-flask

谈一谈 flask

从http 请求开始到响应

前置技能 wsgi

WSGI,全称 Web Server Gateway Interface,或者 Python Web Server Gateway Interface ,是为 Python 语言定义的 Web 服务器和 Web 应用程序或框架之间的一种简单而通用的接口。自从 WSGI 被开发出来以后,许多其它语言中也出现了类似接口。

WSGI 的官方定义是,the Python Web Server Gateway Interface。从名字就可以看出来,这东西是一个Gateway,也就是网关。网关的作用就是在协议之间进行转换。

WSGI 是作为 Web 服务器与 Web 应用程序或应用框架之间的一种低级别的接口,以提升可移植 Web 应用开发的共同点。WSGI 是基于现存的 CGI 标准而设计的。

很多框架都自带了 WSGI server ,比如 Flask,webpy,Django、CherryPy等等。当然性能都不好,自带的 web server 更多的是测试用途,发布时则使用生产环境的 WSGI server或者是联合 nginx 做 uwsgi 。

在网上搜过WSGI的人应该会看到一个图,左边是Server,右边是APP,中间有一个连接纽带是WSGI。

不过,我看了源码以后的理解和这个有些不同,我个人觉得,实际上不应该单独写一个APP,因为,这个WSGI的使用方法实际上也是包含在APP里面的,最右端的app实际上应该指的是逻辑功能,包括URL和view function的对应关系。

WSGI其实是作为一个接口,来接受Server传递过来的信息, 然后通过这个接口调用后台app里的view function进行响应。

起到一个接口的功能,前面对接服务器,后面对接app的具体功能

def application(environ, start_response):               # 一个符合wsgi协议的应用程序写法应该接受2个参数
    start_response('200 OK', [('Content-Type', 'text/html')])  # environ为http的相关信息,如请求头等 start_response则是响应信息
    return [b'<h1>Hello, web!</h1>']        # return出来是响应内容

但是,作为app本身,你就算启动了程序,你也没办法给application传递参数?

所以,实际上,调用application和传递2个参数的动作,是服务器来进行的,比如Gunicorn.

而这个叫做application的东西,在Flask框架内部的名字,叫做wsgi_app,请看下面章节的源码。

from flask import Flask  

app = Flask(__name__)         #生成app实例  

@app.route('/')  
def index():  
        return 'Hello World'  

这样,一个flask app就生成了

但是这里有一个概念必须要搞清楚,就是当你的gunicorn收到http请求,去调用app的时候,他实际上是用了Flask 的 call方法,这点非常重要!!!

因为call方法怎么写,决定了你整个流程从哪里开始。

flask类的call方法

class Flask(_PackageBoundObject):        #Flask类  

#中间省略一些代码  

    def __call__(self, environ, start_response):    #Flask实例的__call__方法  
        """Shortcut for :attr:`wsgi_app`."""  
        return self.wsgi_app(environ, start_response)  #注意他的return,他返回的时候,实际上是调用了wsgi_app这个功能      

如此一来,我们便知道,当http请求从server发送过来的时候,他会启动call功能,最终实际是调用了wsgi_app功能并传入environ和start_response


class Flask(_PackageBoundObject):  

#中间省略一些代码  
                                #请注意函数的说明,说得非常准确,这个wsgi_app是一个真正的WSGI应用  
    def wsgi_app(self, environ, start_response):    #他扮演的是一个中间角色  
        """The actual WSGI application.  This is not implemented in 
        `__call__` so that middlewares can be applied without losing a 
        reference to the class.  So instead of doing this:: 

            app = MyMiddleware(app) 

        It's a better idea to do this instead:: 

            app.wsgi_app = MyMiddleware(app.wsgi_app) 

        Then you still have the original application object around and 
        can continue to call methods on it. 

        :param environ: a WSGI environment 
        :param start_response: a callable accepting a status code, 
                               a list of headers and an optional 
                               exception context to start the response 
        """  
        ctx = self.request_context(environ)  
        ctx.push()  
        error = None  
        try:  
            try:  
                response = self.full_dispatch_request()    #full_dispatch_request起到了预处理和错误处理以及分发请求的作用  
            except Exception as e:  
                error = e  
                response = self.make_response(self.handle_exception(e))  #如果有错误发生,则生成错误响应  
            return response(environ, start_response)       #如果没有错误发生,则正常响应请求,返回响应内容  
        finally:  
            if self.should_ignore_error(error):  
                error = None  
            ctx.auto_pop(error)

WSGI_APP 的内部流程

  1. 生成request请求对象和请求上下文环境
  2. 请求进入预处理,错误处理及请求转发到响应的过程

    class Flask(_PackageBoundObject):  
    
    #此处省略一些代码  
    
    def full_dispatch_request(self):  
        """Dispatches the request and on top of that performs request 
        pre and postprocessing as well as HTTP exception catching and 
        error handling. 
    
        .. versionadded:: 0.7 
        """  
        self.try_trigger_before_first_request_functions()  #进行发生真实请求前的处理  
        try:  
            request_started.send(self)                     #socket部分的操作  
            rv = self.preprocess_request()                 #进行请求的预处理  
            if rv is None:  
                rv = self.dispatch_request()  
        except Exception as e:  
            rv = self.handle_user_exception(e)  
        response = self.make_response(rv)  
        response = self.process_response(response)  
        request_finished.send(self, response=response)  
        return response  
    
  1. 请求分发

class Flask(_PackageBoundObject):  

#省略一些代码  

    def dispatch_request(self):   #看函数定义,matches the URL and returns the value of the view or error.  
        """Does the request dispatching.  Matches the URL and returns the 
        return value of the view or error handler.  This does not have to 
        be a response object.  In order to convert the return value to a 
        proper response object, call :func:`make_response`. 

        .. versionchanged:: 0.7 
           This no longer does the exception handling, this code was 
           moved to the new :meth:`full_dispatch_request`. 
        """  
        req = _request_ctx_stack.top.request  
        if req.routing_exception is not None:  
            self.raise_routing_exception(req)  
        rule = req.url_rule  
        # if we provide automatic options for this URL and the  
        # request came with the OPTIONS method, reply automatically  
        if getattr(rule, 'provide_automatic_options', False) \  
           and req.method == 'OPTIONS':  
            return self.make_default_options_response()  
        # otherwise dispatch to the handler for that endpoint  
        return self.view_functions[rule.endpoint](**req.view_args)   #最终进入view_functions,取出url对应的视图函数的返回值

req = _request_ctx_stack.top.request 可以暂时理解为,将请求对象赋值给req

这里先简单讲下,每个url进来以后,他都会对应一个view_function

另外说下view_functions 是一个字典形式,他的key和value的关系是endpoint ——> view function

所以每个有效的URL进来,都能找到他对应的视图函数view function,取得返回值并赋值给 rv

这时候,通过make_response函数,将刚才取得的 rv 生成响应,重新赋值response

再通过process_response功能主要是处理一个after_request的功能,比如你在请求后,要把数据库连接关闭等动作,和上面提到的before_request对应和类似。

之后再进行request_finished.send的处理,也是和socket处理有关,暂时不详细深入。

之后返回新的response对象

这里特别需要注意的是,make_response函数是一个非常重要的函数,他的作用是返回一个response_class的实例对象,也就是可以接受environ和start_reponse两个参数的对象

  1. 返回wsgi_app 内部

当response从刚刚的full_dispatch_request功能返回之后,函数会对这个response加上environ, start_response的参数并返回给Gunicorn

至此,一个HTTP从请求到响应的流程就完毕了.