Flask request,g,session的實現原理,flaskrequest
最近一直在研究Flask,由於gfirefly中提供的Http介面使用了Flask,以前都是寫一些遊戲中簡單的操作,最近涉及到Flask的方面比較多,所以就認真研究了下。對Flask的request context和app context略有心得,所以和小夥伴們分享一下Flask的request原理。
在我們視圖中要使用request時只需要from flask import request就可以了
很好奇在多線程的環境下,是如何保證request沒有混亂的
在flask.globals.py中
def _lookup_req_object(name): top = _request_ctx_stack.top if top is None: raise RuntimeError('working outside of request context') return getattr(top, name)_request_ctx_stack = LocalStack()request = LocalProxy(partial(_lookup_req_object, 'request'))session = LocalProxy(partial(_lookup_req_object, 'session'))其實可以看到不管request還是session最後都是通過getattr(top, name)擷取的,也就是說肯定有一個上下文
對象同時保持request和session。我們只要一處匯入request,在任何視圖函數中都可以使用request,
關鍵是每次的都是不同的request對象,說明擷取request對象肯定是一個動態操作,不然肯定都是相同的request。這裡的魔法就是_lookup_req_object函數和LocalProxy組合完成的。
LocalProxy是werkzeug.local.py中定義的一個代理對象,它的作用就是將所有的請求都發給內部的_local對象
class LocalProxy(object): def __init__(self, local, name=None): #LocalProxy的代碼被我給簡化了,這裡的local不一定就是local.py中定義的線程局部對象,也可以是任何可調用對象 #在我們的request中傳遞的就是_lookup_req_object函數 object.__setattr__(self, '_LocalProxy__local', local) object.__setattr__(self, '__name__', name) def _get_current_object(self): #很明顯,_lookup_req_object函數沒有__release_local__ if not hasattr(self.__local, '__release_local__'): return self.__local() try: return getattr(self.__local, self.__name__) except AttributeError: raise RuntimeError('no object bound to %s' % self.__name__) def __getattr__(self, name): return getattr(self._get_current_object(), name)當我們調用request.method時會調用_lookup_req_object,對request的任何調用都是對_lookup_req_object返回對象的調用。
既然每次request都不同,要麼調用top = _request_ctx_stack.top返回的top不同,要麼top.request屬性不同,在flask中每次返回的top是不一樣的,所以request的各個屬性都是變化的。
現在需要看看_request_ctx_stack = LocalStack(),LocalStack其實就是簡單的類比了堆棧的基本操作,push,top,pop,內部儲存的執行緒區域變數是在多線程中request不混亂的關鍵。
class Local(object): __slots__ = ('__storage__', '__ident_func__') def __init__(self): object.__setattr__(self, '__storage__', {}) object.__setattr__(self, '__ident_func__', get_ident) def __getattr__(self, name): return self.__storage__[self.__ident_func__()][name] 簡單看一下Local的代碼,__storage__為內部儲存的自己,鍵就是thread.get_ident,也就是根據線程的標示符返回對應的值。
下面我們來看看整個互動過程,_request_ctx_stack堆棧是在哪裡設定push的,push的應該是我們上面說的同時具有request和session屬性的對象,那這傢伙又到底是什嗎?
flask從app.run()開始
class Flask(_PackageBoundObject): def run(self, host=None, port=None, debug=None, **options): from werkzeug.serving import run_simple run_simple(host, port, self, **options)
使用的是werkzeug的run_simple,根據wsgi規範,app是一個介面,並接受兩個參數,即,application(environ, start_response)
在run_wsgi的run_wsgi我們可以清晰的看到調用過程
def run_wsgi(self): environ = self.make_environ() def start_response(status, response_headers, exc_info=None): if exc_info: try: if headers_sent: reraise(*exc_info) finally: exc_info = None elif headers_set: raise AssertionError('Headers already set') headers_set[:] = [status, response_headers] return write def execute(app): application_iter = app(environ, start_response) #environ是為了給request傳遞請求的 #start_response主要是增加回應標頭和狀態代碼,最後需要werkzeug發送請求 try: for data in application_iter: #根據wsgi規範,app返回的是一個序列 write(data) #發送結果 if not headers_sent: write(b'') finally: if hasattr(application_iter, 'close'): application_iter.close() application_iter = None try: execute(self.server.app) except (socket.error, socket.timeout) as e: passflask中通過定義__call__方法適配wsgi規範
class Flask(_PackageBoundObject): def __call__(self, environ, start_response): """Shortcut for :attr:`wsgi_app`.""" return self.wsgi_app(environ, start_response) def wsgi_app(self, environ, start_response): ctx = self.request_context(environ) #這個ctx就是我們所說的同時有request,session屬性的上下文 ctx.push() error = None try: try: response = self.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) def request_context(self, environ): return RequestContext(self, environ)
哈哈,終於找到神秘人了,RequestContext是保持一個請求的上下文變數,之前我們_request_ctx_stack一直是空的,當一個請求來的時候調用ctx.push()將向_request_ctx_stack中push ctx。
我們看看ctx.push
class RequestContext(object): def __init__(self, app, environ, request=None): self.app = app if request is None: request = app.request_class(environ) #根據環境變數建立request self.request = request self.session = None def push(self): _request_ctx_stack.push(self) #將ctx push進 _request_ctx_stack # Open the session at the moment that the request context is # available. This allows a custom open_session method to use the # request context (e.g. code that access database information # stored on `g` instead of the appcontext). self.session = self.app.open_session(self.request) if self.session is None: self.session = self.app.make_null_session() def pop(self, exc=None): rv = _request_ctx_stack.pop() def auto_pop(self, exc): if self.request.environ.get('flask._preserve_context') or \ (exc is not None and self.app.preserve_context_on_exception): self.preserved = True self._preserved_exc = exc else: self.pop(exc)
我們看到ctx.push操作將ctx push到_request_ctx_stack,所以當我們調用request.method時將調用_lookup_req_object。top此時就是ctx內容物件,而getattr(top, "request")將返回ctx的request,而這個request就是在ctx的__init__中根據環境變數建立的。
哈哈,明白了吧,每一次調用視圖函數操作之前,flask會把建立好的ctx放線上程Local中,當使用時根據線程id就可以拿到了。在wsgi_app的finally中會調用ctx.auto_pop(error),會根據情況判斷是否清除放_request_ctx_stack中的ctx。
上面是我簡化的代碼,其實在RequestContext push中_app_ctx_stack = LocalStack()是None,也會把app push進去,對應的app內容物件為AppContext。
我們知道flask還有一個神秘的對象g,flask從0.10開始g是和app綁定在一起的(http://flask.pocoo.org/docs/0.10/api/#flask.g),g是AppContext的一個成員變數。雖然說g是和app綁定在一起的,但不同請求的AppContext是不同的,所以g還是不同。也就是說你不能再一個視圖中設定g.name,然後再另一個視圖中使用g.name,會提示AttributeError。
到這裡,不知道你對RequestContext還有沒有疑惑,這裡有一點比較疑惑的是我們當前request只有一個,為什麼要request要使用棧,而不是直接儲存當前的request執行個體?
其實這主要是為了多app共存考慮的,由於我們一般都只有一個app,所以棧頂存放的肯定是當前request對象,當如果是多個app,那麼棧頂存放的是當前活躍的request,也就是說使用棧是為了擷取當前的活躍request對象。
下面使用gtwisted類比多個app,由於gtwisted使用了greenlet,所以多個app.run並不會阻塞,當然你也可以使用線程來類比。
from flask import Flask, url_forfrom gtwisted.core import reactorapp1 = Flask("app1")app2 = Flask("app2")@app1.route("/index1")def index1(): return "app1"@app1.route("/home")def home(): return "app1home"@app2.route("/index2")def index2(): return "app2" # reactor.listenWSGI(8000, app1)# reactor.listenWSGI(8001, app2)# reactor.run()with app1.test_request_context(): print url_for('index1') with app2.test_request_context(): print url_for('index2') print url_for('home')
如果將中間三行去掉,可以通過瀏覽器127.0.0.1:8000/index1,127.0.0.1:80001/index2訪問多個app
輸出結果:
當app1.test_request_context()時,會將app1對應的context壓棧,當前活躍app context是app1的,所以url_for使用的是app1的context,當with app2.test_request_context()時,會將app2對應的context壓棧,當前活躍app context是app2的,當with過了範圍,將彈出app2的context,此時活躍的為app1的,這就是為什麼context使用棧而不是執行個體變數。
到這裡各位小夥伴們都明白了吧,flask以優雅的方式給我們提供了很大的便利,自己做了很多的工作,這就是當代活雷鋒!!!
Globalasax中的Application_EndRequest事件,為何不可以對session進行操作?
Application_End事件,是當伺服器停止時進行的操作,或重新啟動時才能用的Application_Endg事件。所以,你在看來session是沒有被進行操作的。
flask怎得到session退出時的事件?
flask裡面的session預設關閉瀏覽器就失效.線上時間長度可以從使用者開啟頁面到瀏覽器觸發beforeunload事件的這段時間來計算