以request爲例,因爲request最簡單。
一個完整的app應用程序如下:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "hello world"
if __name__ == "__main__":
app.__call__
app.run()
#app.run() 程序執行起來,內部執行了run_simple
#run_simple(host, port, self, **options)
#第三個參數是self,最後會執行__call__方法:
一、將請求相關的東西做了一次封裝
flask類中:
app.run方法中:
其中self指的是app,run_simple會執行app.__call__方法:
flask中的__call__方法,調用了flask中的wsgi_app方法,該方法中執行了請求相關的所有操作:
1、首先執行了ctx = self.request_context(environ),其中environ是請求相關的所有數據
request_context方法實例化了一個 RequestContext對象,執行RequestContext類中__init__方法:
在RequestContext類的__init__方法,因爲request是None,將執行app.request_class方法,其中app是Flask類的實例對象 ,在Flask類中可以看到,Flask將請求相關的操作又封裝到了一個Request類中,RequestContext不僅包含請求,還包括session,flaskes等。
2、然後執行ctx.push()
ctx是RequestContext類的實例化對象,所以會執行RequestContext類中的push方法:
該方法中注意_request_ctx_stack.push(self),其中self是RequestContext對象,其中包含了請求相關的所有數據。
而_request_ctx_stack在globals.py中,是在程序剛開始運行時就創建的一個全局變量:
LocalStack裏封裝的Local對象:
LocalStack裏的push方法會調用Local類的__setattr__,根據線程或協程唯一id將數據保存在各自的字典中: