Get the user id in flask

Viewed 14213

Note. Not duplicated of Get current user id in Flask.

I use flask_login and flask, so to get the current id its only flask_login.current_user.id. But the problem occurs when I want to create a variable with the command, like, in my app.py:

...
curr_user = flask_login.current_user.id

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

That says:

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

Only when running (don't need to be called, the only assignment of value to curr_user do the problem)

Tried calling the function w/variable as flask_login.current_user.id and Ive the same.

I think the trouble is because I cant get the id of user in general (in the app.py running instance), and that need context. So, I tried:

with app.test_request_context():

before assignment, and I got only None for users and guests.

Edit. I know I can just do:

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

But that was only an example, the really need is the assignment of value to a non-local variable with context.

1 Answers

You could save the user_id in the app context using "g":

from flask import g

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

But the simplest solution would be just to pass the user id to the function that you're calling.

# 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'
Related