怎么理解flask的这段代码呢?
有人能解释一下这一行吗?
g = LocalProxy(lambda: _request_ctx_stack.top.g)
Local Flask
from werkzeug import LocalStack, LocalProxy
# context locals
_request_ctx_stack = LocalStack()
current_app = LocalProxy(lambda: _request_ctx_stack.top.app)
request = LocalProxy(lambda: _request_ctx_stack.top.request)
session = LocalProxy(lambda: _request_ctx_stack.top.session)
g = LocalProxy(lambda: _request_ctx_stack.top.g)
代码的代码在这里: http://pastebin.com/U3e1bEi0
Could anyone explain this line?
g = LocalProxy(lambda: _request_ctx_stack.top.g)
code from flask
from werkzeug import LocalStack, LocalProxy
# context locals
_request_ctx_stack = LocalStack()
current_app = LocalProxy(lambda: _request_ctx_stack.top.app)
request = LocalProxy(lambda: _request_ctx_stack.top.request)
session = LocalProxy(lambda: _request_ctx_stack.top.session)
g = LocalProxy(lambda: _request_ctx_stack.top.g)
code of Local is here: http://pastebin.com/U3e1bEi0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
LocalStack 和 LocalProxy 的 Werkzeug 文档 可能会有所帮助,以及对 < a href="http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface" rel="nofollow">WSGI。
看起来正在发生的事情是创建了一个全局(但空)堆栈
_request_ctx_stack
。这适用于所有线程。某些 WSGI 样式对象(current_app
、request
、session
和g
)设置为使用顶部项目在全局堆栈中。在某一时刻,一个或多个 WSGI 应用程序被推送到全局堆栈上。然后,例如,当在运行时使用
current_app
时,将使用当前的顶级应用程序。如果堆栈从未初始化,则 top 将返回 None,并且您将收到类似 AttributeError: 'NoneType' object has no attribute 'app' 的异常。The Werkzeug documentation for LocalStack and LocalProxy might help, as well as some basic understanding of WSGI.
It appears what is going on is that a global (but empty) stack
_request_ctx_stack
is created. This is available to all threads. Some WSGI-style objects (current_app
,request
,session
, andg
) are set to use the top item in the global stack.At some point, one or more WSGI applications are pushed onto the global stack. Then, when, for example,
current_app
is used at runtime, the current top application is used. If the stack is never initialized, then top will return None and you'll get an exception likeAttributeError: 'NoneType' object has no attribute 'app'
.