Flask源码

2017-09-22  本文已影响0人  idri
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
    return "Hello World!"
if __name__ == '__main__':
    app.run()

实例化Flask应用时,会创造一个Jinja环境。
实例化的Flask应用是一个可调用对象。
WSGI规范这个对象以便于服务器或者网关调用。
__call__(environ, start_respose)方法,environ由服务器产生,start_response在服务器中定义。

def wsgi_app(environ, start_response):
    with self.request_context(environ):
        ...

request_context(environ)_RequestContext的实例。
with 语句方法,__enter__, __exit__

class _RequestContext(object):
    """The request context contains all request relevant information.  It is
    created at the beginning of the request and pushed to the
    `_request_ctx_stack` and removed at the end of it.  It will create the
    URL adapter and request object for the WSGI environment provided.
    """
 
    def __init__(self, app, environ):
        self.app = app
        self.url_adapter = app.url_map.bind_to_environ(environ)
        self.request = app.request_class(environ)
        self.session = app.open_session(self.request)
        self.g = _RequestGlobals()
        self.flashes = None
 
    def __enter__(self):
        _request_ctx_stack.push(self)
 
    def __exit__(self, exc_type, exc_value, tb):
        # do not pop the request stack if we are in debug mode and an
        # exception happened.  This will allow the debugger to still
        # access the request object in the interactive shell.
        if tb is None or not self.app.debug:
            _request_ctx_stack.pop()

请求上下文对象会通过local模块,压入栈中。使用with语句结束后,上下文对象被销毁。

上下文

上一篇 下一篇

猜你喜欢

热点阅读