首页 > 解决方案 > 无法在 MethodView 中使用 flask_login 访问当前用户 ID

问题描述

在基于类的视图中访问 POST 请求中的用户 ID 时遇到问题。在 GET 方法中,我可以轻松获取数据。我想问题是因为我的 POST 方法没有用 装饰@login_required,但是由于出现错误,我无法装饰 POST,访问记录的用户 ID 的解决方法是什么?

验证.py

class Authenticate(MethodView):

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

在这个类中,我想访问用户 id

class User(MethodView):

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

标签: flaskflask-login

解决方案


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


推荐阅读