创建对象

from flask import Flask 

"""
1 实例化对象 app 
""" 
app = Flask(__name__)

"""
2 设置路由
    将路由关系放在 app.url_map = {} 中
"""
@app.route("/index")
def index():
    return "index"

if__name__ == "__main__":
"""
3 启动socket服务端 
"""
    app.run()

"""
4 用户请求到来就会执行 __call__ 方法 
"""

run

# 启动入口简约版代码  
from werkzeug.wrappers import Response
from werkzeug.serving import run_simple

class Flask(object):
    def __call__(self,environ, start_response):
        response = Response('hello')
        return response(environ, start_response)

    def run(self):
        run_simple('127.0.0.1', 8000, self)

run_simple(host,port,self,**options)
会对第三个传入的参数加()进行执行
第三个参数如果是app对象就执行其 __call__ 方法

__call__ 

def __call__(self,environ, start_response):
    # environ 请求相关的所有数据 第一手的数据,由wsgi进行的初步封装
    # start_response 用于设置响应相关数据 
    return wsgi_app(environ,start_response)

 call 返回的是 wsgi_app 的执行结果

wsgi_app

wsgi_app 里面做的事情就很多了。

我们一步一步来看

第一步 ctx 封装

Flask 源码流程,上下文管理

首先把请求相关的所有数据都 封装了到 一个 ctx 对象

Flask 源码流程,上下文管理

而且通过 __init__ 可以看到 封装了 request 以及创建了一个 空的 session 

Flask 源码流程,上下文管理

第一步总结

  得到了 ctx 对象

  创建ctx.request 以及 ctx.session = None 

第二步 push

 Flask 源码流程,上下文管理

 来看下 push 都做了什么

 Flask 源码流程,上下文管理

 封了一个top,这是啥不知道,要继续看是个 LocalStack 对象

 Flask 源码流程,上下文管理

class LocalStack(object):

    """This class works similar to a :class:`Local` but keeps a stack
    of objects instead.  This is best explained with an example::

        >>> ls = LocalStack()
        >>> ls.push(42)
        >>> ls.top
        42
        >>> ls.push(23)
        >>> ls.top
        23
        >>> ls.pop()
        23
        >>> ls.top
        42

    They can be force released by using a :class:`LocalManager` or with
    the :func:`release_local` function but the correct way is to pop the
    item from the stack after using.  When the stack is empty it will
    no longer be bound to the current context (and as such released).

    By calling the stack without arguments it returns a proxy that resolves to
    the topmost item on the stack.

    .. versionadded:: 0.6.1
    """

    def __init__(self):
        self._local = Local()

    def __release_local__(self):
        self._local.__release_local__()

    def _get__ident_func__(self):
        return self._local.__ident_func__

    def _set__ident_func__(self, value):
        object.__setattr__(self._local, '__ident_func__', value)
    __ident_func__ = property(_get__ident_func__, _set__ident_func__)
    del _get__ident_func__, _set__ident_func__

    def __call__(self):
        def _lookup():
            rv = self.top
            if rv is None:
                raise RuntimeError('object unbound')
            return rv
        return LocalProxy(_lookup)

    def push(self, obj):
        """Pushes a new item to the stack"""
        rv = getattr(self._local, 'stack', None)
        if rv is None:
            self._local.stack = rv = []
        rv.append(obj)
        return rv

    def pop(self):
        """Removes the topmost item from the stack, will return the
        old value or `None` if the stack was already empty.
        """
        stack = getattr(self._local, 'stack', None)
        if stack is None:
            return None
        elif len(stack) == 1:
            release_local(self._local)
            return stack[-1]
        else:
            return stack.pop()

    @property
    def top(self):
        """The topmost item on the stack.  If the stack is empty,
        `None` is returned.
        """
        try:
            return self._local.stack[-1]
        except (AttributeError, IndexError):
            return None
LocalStack 源码

相关文章: