问题
I am trying to learn to make a variable available across method through a decorator function in Flask.
I read Flask request context documentation and wrote the following code, which works as intended.
a.py
_request_ctx_stack.top.current_identity = payload.get('sub')
b.py
current_identity = getattr(_request_ctx_stack.top, 'current_identity', None)
However flask-jwt solves this problem by introducing an additional local proxy
like this:
a.py
from werkzeug.local import LocalProxy
current_identity = LocalProxy(lambda: getattr(_request_ctx_stack.top, 'current_identity', None))
_request_ctx_stack.top.current_identity = payload.get('sub')
b.py
from a import current_identity
Why? I read werkzeug context locals documentation and doesn't Flask already implements Werkzeug context locals for request object?
Is there any advantage of introducing LocalProxy
?
回答1:
The LocalProxy
wraps the manual code you wrote for getting the value. Instead of needing that manual code everywhere you want to access current_identity
, you access it as a proxy and it does the manual code for you.
It's most useful in libraries, where users wouldn't be expected to know how current_identity
is set up, and would import the proxy to access it. The same applies to Flask itself: you're not expected to know how the request is set up, or where exactly it's stored, only that you access it by importing request
.
A proxy is useful for data that is set up during and local to each request. If you used a true global variable, it would not behave the way you expect when multiple requests are being handled. See Are global variables thread safe in flask? How do I share data between requests?
来源:https://stackoverflow.com/questions/56132596/how-does-context-locals-and-the-request-context-work-together