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
To run the app outside of the VS Code debugger, use the following steps from a terminal: Set an environment variable for FLASK_APP . On Linux and macOS, use export set FLASK_APP=webapp ; on Windows use set FLASK_APP=webapp . Navigate into the hello_app folder, then launch the program using python -m flask run .
Flask Documentation on __name__ It is described as "the name of the application package". The documentation suggests that you "usually" create the Flask instance by passing __name__ for this argument, without going into any details on why.
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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With