Flask源碼

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語句結束后,上下文對象被銷毀。

  • 應用上下文
    創建 Request_context時,先檢查是否另一個棧存在app_context,若無則創建一個。
    離開請求上下文時,先銷毀請求上下文,如果需要,再銷毀應用上下文。
    應用上下文作用:支持多應用
    應用上下文是包含應用信息的。
    current_app 就是對 _app_ctx_stack.top.app 的引用。

上下文

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容