How to understand this code of flask?


Question

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

1
8
9/4/2013 4:52:34 PM

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

4
9/29/2016 9:36:17 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon