简体   繁体   中英

Cannot access current user id using flask_login in MethodView

I have a problem accessing user-id inside a POST request in Class-based views. Inside a GET method, I can easily get data. I guess the problem is because my POST method is not decorated with @login_required , but I cannot decorate POST since getting an error, what is a workaround to access logged user id?

Authenticate.py

class Authenticate(MethodView):

  def post(self):
    ...some code
    login_user(user, remember=True)
    g.user = current_user.id

In this class, I want to access users id

class User(MethodView):

  def post(view):
    # not working
    print(current_user.id)
    print(g.user) 

When using Flask-Login, you should have user_loader callback function

from flask_login import LoginManager

app = Flask(__name__)
login_manager = LoginManager(app)

@app.login_manager.user_loader
def load_user(_id):
    user = users[_id]
    return user

This assumes that your login or authenticate endpoint saved the user somewhere before login_user . For simplicity the above snippet stores it in python dictionary where key is your unique user_id and the value is your user's information.

Now when any of your endpoints are called, this user_loader callback function is called and the current_user object is populated with your the returned user ( return user )

For your code it might work like that

  def post(self):
    ...some code
    ## New code ##
    save_user(user._id, user)
    login_user(user, remember=True)
    return {"state":"authenticated"}, 200

Of course save_user() should save the user somewhere accessible by the user_loader callback

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