Context Locals和Request Context如何一起工作? [英] How does Context Locals and The Request Context work together?
问题描述
我正在尝试通过Flask中的装饰器函数来学习如何在整个方法中使用变量.
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)
但是 flask-jwt 通过引入其他类似的local proxy
解决了这个问题:
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
为什么?我阅读了 werkzeug上下文本地文档,并且Flask还没有实现Werkzeug上下文当地人的请求对象?
Why? I read werkzeug context locals documentation and doesn't Flask already implements Werkzeug context locals for request object?
引入LocalProxy
有什么好处吗?
推荐答案
LocalProxy
包装您为获取值而编写的手册代码.无需在要访问current_identity
的任何地方都需要该手册代码,而是将其作为代理进行访问,它会为您执行手册代码.
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.
它在库中最有用,因为库中不会期望用户知道current_identity
的设置方式,并且会导入代理来访问它.这对Flask本身同样适用:您不希望知道请求的设置方式或确切的存储位置,只是通过导入request
即可访问它.
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?
这篇关于Context Locals和Request Context如何一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!