Flask 上下文(应用程序和请求)与线程局部变量
Flask contexts (application and request) vs thread-local variables
from flask import request
@app.route('/')
def index():
user_agent = request.headers.get('User-Agent')
return '<p>Your browser is %s</p>' % user_agent
Note how in this view function request
is used as if it was a global
variable. In reality, request
cannot be a global variable if you
consider that in a multithreaded server the threads are working on
different requests from different clients at the same time, so each
thread needs to see a different object in request. Contexts enable
Flask to make certain variables globally accessible to a thread
without interfering with the other threads.
可以理解,但为什么不直接将 request
设为 thread-local variable?在幕后,request
到底是什么,它与线程局部变量有何不同?
这只是 Armin(Flask 的作者)的设计决定。您确实可以重写 Flask 以作为本地线程运行,但这不是他在这里想要做的。
Flask(总的来说)的想法是让事情尽可能简单,并抽象出很多想法。这就是为什么很多 Flask 助手被实现为 'global variables' 的原因:你真的不必去思考它背后的含义,因为每个全局都绑定到传入的请求。
from flask import request
@app.route('/')
def index():
user_agent = request.headers.get('User-Agent')
return '<p>Your browser is %s</p>' % user_agent
Note how in this view function
request
is used as if it was a global variable. In reality,request
cannot be a global variable if you consider that in a multithreaded server the threads are working on different requests from different clients at the same time, so each thread needs to see a different object in request. Contexts enable Flask to make certain variables globally accessible to a thread without interfering with the other threads.
可以理解,但为什么不直接将 request
设为 thread-local variable?在幕后,request
到底是什么,它与线程局部变量有何不同?
这只是 Armin(Flask 的作者)的设计决定。您确实可以重写 Flask 以作为本地线程运行,但这不是他在这里想要做的。
Flask(总的来说)的想法是让事情尽可能简单,并抽象出很多想法。这就是为什么很多 Flask 助手被实现为 'global variables' 的原因:你真的不必去思考它背后的含义,因为每个全局都绑定到传入的请求。