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
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'
.