Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand this code of flask?

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

like image 681
chenge Avatar asked Sep 27 '10 01:09

chenge


People also ask

How do I run a Flask code?

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 .

What is the meaning of Flask (__ name __)?

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.


1 Answers

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

like image 137
jwhitlock Avatar answered Oct 07 '22 06:10

jwhitlock