获取flask中的用户id

Get the user id in flask

注意。不与 Get current user id in Flask.

重复

我使用 flask_login 和 flask,所以要获取当前 ID,它只有 flask_login.current_user.id。但是当我想用命令创建一个变量时,问题就出现了,比如,在我的 app.py:

...
curr_user = flask_login.current_user.id

def function_a(curr_user):
    os.mkdir(path + '/' + curr_user)
    return 'Path created successfully'
...

也就是说:

AttributeError: 'NoneType' object has no attribute 'get_id'

只有在运行时(不需要调用,只给curr_user赋值做题)

尝试将函数 w/variable 调用为 flask_login.current_user.id,我也一样。

我认为麻烦是因为我无法获取一般用户的 ID(在 app.py 运行 实例中),这需要上下文。所以,我尝试了:

with app.test_request_context():

分配之前,我只得到 None 用户和来宾。

编辑。我知道我可以做到:

def function_a():
    os.mkdir(path+'/'+flask_login.current_user.id)
    return 'Path created successfully'

但这只是一个例子,真正需要的是为具有上下文的非局部变量赋值。

您可以使用 "g":

在应用上下文中保存 user_id
from flask import g

if current_user.is_authenticated():
        g.user = current_user.get_id()

但最简单的解决方案是将用户 ID 传递给您正在调用的函数。

# call this function from inside the app/request context
def function_a(user_id):
    os.mkdir(os.path.join(path,user_id))
    return 'Path created successfully'