[英]flask_login, How to get current_user from a new thread?
I'm new to flask_login library. 我是flask_login库的新手。 In my codebase, after user login, I can get the current user information from
current_user
of flask_login
library. 在我的代码库中,用户登录后,我可以从
flask_login
库的current_user
获取当前用户信息。 The simplified test code is below: 简化的测试代码如下:
from threading import Thread
from flask_login import current_user
def test():
print("current_user = ", current_user) # None
worker = Thread(target=test)
worker.start()
print("current_user = ", current_user) # <XXX.auth.view.User object at 0x119b2b250>
So I'm very confusing why I can't get the current user information from a separate thread, even after I deliberately import again before the first print
statement. 所以我很困惑,为什么我无法从单独的线程获取当前用户信息,即使我在第一个
print
语句之前再次故意导入。
Thanks. 谢谢。
current_user
is a thread-local value - it will behave as a separate variable in every thread. current_user
是一个线程局部值 - 它将在每个线程中表现为一个单独的变量。 You must pass it between threads if you need it elsewhere. 如果您在其他地方需要它,您必须在线程之间传递它。
Perhaps your call would become: 也许你的电话会变成:
from threading import Thread
from flask_login import current_user
user = current_user
def test(user):
print("current_user = ", user)
worker = Thread(target=test, args=(user,))
worker.start()
print("current_user = ", user)
Relevant line from the flask_login
source: 来自
flask_login
源的相关行:
current_user = LocalProxy(lambda: _get_user())
https://github.com/maxcountryman/flask-login/blob/d22f80d166ee260d44e0d2d9ea973b784ef3621b/flask_login/utils.py#L26 https://github.com/maxcountryman/flask-login/blob/d22f80d166ee260d44e0d2d9ea973b784ef3621b/flask_login/utils.py#L26
Relevant discussion of werkzeug's implementations of locals from the werkzeug docs: 关于werkzeug从werkzeug文档中实现本地人的相关讨论:
Werkzeug provides its own implementation of local data storage called werkzeug.local.
Werkzeug提供了自己的本地数据存储实现,称为werkzeug.local。 This approach provides a similar functionality to thread locals but also works with greenlets.
此方法为线程本地提供了类似的功能,但也适用于greenlet。
https://werkzeug.palletsprojects.com/en/0.15.x/local/#werkzeug.local.LocalProxy https://werkzeug.palletsprojects.com/en/0.15.x/local/#werkzeug.local.LocalProxy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.