Get the user id in flask
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 videos on Youtube
sebach1
Updated on June 04, 2022Comments
-
sebach1 over 1 year
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.
-
Dani G about 5 yearsWhere are you calling function_a from? looks like you're out of app context.
-
sebach1 about 5 yearsWell I assign the value in app.py, but the function_a is from another file (decorators.py). Can you help me on how I can use the decorators with context? If its possible, trying not to import app.py on decorators (bcs app import decorators at the same time). Thanks u
-