怎么理解flask的这段代码呢?

发布于 2024-09-25 04:20:58 字数 587 浏览 8 评论 0原文

有人能解释一下这一行吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别忘他 2024-10-02 04:20:58

LocalStack 和 LocalProxy 的 Werkzeug 文档 可能会有所帮助,以及对 < a href="http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface" rel="nofollow">WSGI。

看起来正在发生的事情是创建了一个全局(但空)堆栈_request_ctx_stack。这适用于所有线程。某些 WSGI 样式对象(current_apprequestsessiong)设置为使用顶部项目在全局堆栈中。

在某一时刻,一个或多个 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, and g) 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 like AttributeError: 'NoneType' object has no attribute 'app'.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文