简体   繁体   中英

flask_login, How to get current_user from a new thread?

I'm new to flask_login library. In my codebase, after user login, I can get the current user information from current_user of flask_login library. 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.

Thanks.

current_user is a thread-local value - it will behave as a separate variable in every thread. 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:

current_user = LocalProxy(lambda: _get_user())

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 provides its own implementation of local data storage called werkzeug.local. This approach provides a similar functionality to thread locals but also works with greenlets.

https://werkzeug.palletsprojects.com/en/0.15.x/local/#werkzeug.local.LocalProxy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM