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 的引用。